【问题标题】:Why react-intl is not stable when using formatDate with same argument on different computer time zones?为什么在不同的计算机时区使用具有相同参数的 formatDate 时 react-intl 不稳定?
【发布时间】:2018-04-19 14:46:19
【问题描述】:

我正在从服务器获取时间戳

const date = 1420070399999

在控制台中产生:

新日期(日期)=> 2014 年 12 月 31 日星期三 23:59:59 GMT+0000 (UTC)

然后对其应用以下排列(这里momentmoment@2.22.1intl 是使用injectIntl 来自react-intl 包` 的属性):

  const momentSimple = moment.utc(date);
  const momentFormatted = momentSimple.format(dateFormat);
  const defaultFormatSimple = intl.formatDate(momentSimple);
  const defaultFormatFormatted = intl.formatDate(momentFormatted);
  const formattedFormatSimple = intl.formatDate(momentSimple, { year: 'numeric', month: 'long' });
  const formattedFormatFormatted = intl.formatDate(momentFormatted, { year: 'numeric', month: 'long' });

当我的计算机时区设置为 美国托莱多(中美洲时间)时,这些变量(从第二个开始,不包括第一个)具有以下值:

"December 2014"
"12/31/2014"
"11/30/2014"
"December 2014"
"November 2014"

但是当我切换到日本东京时,我得到了这个:

"December 2014"
"1/1/2015"
"12/1/2014"
"January 2015"
"December 2014"

如您所见,托莱多有 12 月/11 月,东京有 1 月/12 月。

为什么会这样?

【问题讨论】:

    标签: javascript reactjs internationalization momentjs react-intl


    【解决方案1】:

    所以我发现问题在于我将月/年字符串提供给 formatDate 方法(例如 December 2014 ),该方法在运行时浏览器时区中将其消化为 2014 年 12 月的午夜,所以如果我在东京,尊重的 UTC 当地时间月份变成了 11 月,因为它在东京之后

    我应该使用timeZone 选项,作为第二个参数传递给intl.formatDate() 方法,如documentation for this method 中的type DateTimeFormatOptions ... 声明中所述。这将强制 react-intl 底层 Intl JS API 方法 formatDate 将作为第一个参数提供的日期视为 UTC。

      const momentSimple = moment.utc(date);
      const momentFormatted = momentSimple.format(dateFormat);
      const defaultFormatSimple = intl.formatDate(momentSimple, { timeZone: 'UTC' });
      const defaultFormatFormatted = intl.formatDate(momentFormatted, { timeZone: 'UTC' });
      const formattedFormatSimple = intl.formatDate(momentSimple, { year: 'numeric', month: 'long', timeZone: 'UTC' });
      const formattedFormatFormatted = intl.formatDate(momentFormatted, { year: 'numeric', month: 'long', timeZone: 'UTC' });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-12
      • 2019-02-08
      • 1970-01-01
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 2017-07-31
      • 1970-01-01
      相关资源
      最近更新 更多