How to format date/time in a specific timezone with the JavaScript date-fns library

社会主义新天地 提交于 2019-12-23 15:01:06

问题


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}
)

How can I specify a timezone?


回答1:


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.

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' })

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>


来源:https://stackoverflow.com/questions/45685066/how-to-format-date-time-in-a-specific-timezone-with-the-javascript-date-fns-libr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!