如何使用JavaScript date-fns库格式化特定时区的日期/时间
有没有办法使用 date-fns 库格式化/输出指定时区的日期?我可以很容易地格式化日期:
Is there a way to format/output a date in a specified timezone with the date-fns library? I can format a date easily enough:
format(
new Date(),
'MM/DD/YYYY'
)
我可以指定一个区域设置(来自他们的文档):
And I can specify a locale (from their docs):
var eoLocale = require('date-fns/locale/eo')
var result = format(
new Date(2014, 6, 2),
'Do [de] MMMM YYYY',
{locale: eoLocale}
)
如何指定时区?
我担心你必须等待 date-fns 直到版本2.0发布。时区支持尚未完成,很可能只添加到新版本,其中解析和格式化有望得到改善。
I am afraid, that you will have to wait for the time zone support in date-fns
till the version 2.0 is released. The time zone support has not been finished yet and it is likely to be added only to the new version, where parsing and formatting is expected to be improved.
同时,你必须到达其他库,允许任意格式化时区。例如, Moment.js 或 Day.js :
In the meanwhile, you have to reach to other libraries, which allow formatting in arbitrary time zone. For example, Moment.js or Day.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的可运行代码段:
Runnable code snippet inserting the result to 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>