6

有没有办法使用date-fns库在指定时区格式化/输出日期?我可以很容易地格式化日期:

format(
  new Date(),
  'MM/DD/YYYY'
)

我可以指定一个语言环境(来自他们的文档):

var eoLocale = require('date-fns/locale/eo')
var result = format(
  new Date(2014, 6, 2),
  'Do [de] MMMM YYYY',
  {locale: eoLocale}
)

如何指定时区?

4

2 回答 2

4

恐怕您将不得不等待时区支持,date-fns直到 2.0 版本发布。时区支持尚未完成,很可能只添加到新版本中,预计解析和格式化将得到改进。

同时,您必须访问其他允许在任意时区格式化的库。例如,Moment.jsDay.js

// Print "06/01/2014 8:00:00 PM GMT-0400 (EDT)"

moment('2014-06-02T00:00:00.000Z')
  .tz('America/New_York')
  .format('MM/DD/YYYY h:mm:ss A [GMT]ZZ (z)')

dayjs('2014-06-02T00:00:00.000Z')
  .format('MM/DD/YYYY h:mm:ss A [GMT]ZZ (z)',
          { timeZone: 'America/New_York' })

将结果插入 HTML 的可运行代码片段:

// Initialise day.js extensions
dayjs.extend(dayjs_plugin_timeZone)

// Prepare the canvas
const output = document.getElementById('output')
output.innerHTML = 'Expected:  06/01/2014 8:00:00 PM GMT-0400 (EDT)\n'


// Print "06/01/2014 8:00:00 PM GMT-0400 (EDT)"

const date1 = moment('2014-06-02T00:00:00.000Z')
  .tz('America/New_York')
  .format('MM/DD/YYYY h:mm:ss A [GMT]ZZ (z)')
output.innerHTML += `Moment.js: ${date1}\n`

const date2 = dayjs('2014-06-02T00:00:00.000Z')
  .format('MM/DD/YYYY h:mm:ss A [GMT]ZZ (z)',
          { timeZone: 'America/New_York' })
output.innerHTML += `Date.js:   ${date2}\n`
<script src="https://unpkg.com/moment@2.24.0/min/moment-with-locales.min.js"></script>
<script src="https://unpkg.com/moment-timezone@0.5.25/builds/moment-timezone-with-data.min.js"></script>

<script src="https://unpkg.com/timezone-support@1.8.1/dist/lookup-convert.umd.js"></script>
<script src="https://unpkg.com/timezone-support@1.8.1/dist/data.umd.js"></script>
<script src="https://unpkg.com/dayjs-ext@2.2.0/dayjs.min.js"></script>
<script src="https://unpkg.com/dayjs-ext@2.2.0/plugin/timeZone.js"></script>

<pre id="output"></pre>

于 2018-09-16T09:22:45.880 回答
1

版本 2 拯救了一天!

  const { startOfDay, endOfDay, format } = require('date-fns') // or use imports
  const { enGb } = require('date-fns/locale/en-GB') // or use imports

  const fromDate = startOfDay(new Date('02-Aug-2001'))
  const toDate = endOfDay(new Date('02-Aug-2001'))
  const from = format(fromDate, 'dd-MMM-yyyy HH:mm:ss', { locale: enGb })
  const to = format(toDate, 'dd-MMM-yyyy HH:mm:ss', { locale: enGb })
  console.log(from) // 02-Aug-2001 00:00:00
  console.log(to) // 02-Aug-2001 23:59:59

https://date-fns.org/v2.21.1/docs/format // 官方文档

https://www.npmjs.com/package/date-fns-tz#user-content-format // 更易于阅读的文档(注意 date-fns-tz 不需要安装)

于 2021-04-16T23:32:12.050 回答