day.js 没有将 UTC 转换为本地时间

rol*_*olu 3 javascript timezone utc momentjs dayjs

我在尝试将momentjs转换为day.js 时遇到问题

瞬间,我将 utc 转换为本地时间,通过moment.utc('2020-04-22T14:56:09.388842').local().format('MM/DD/YY h:mm A')它返回04/22/20 9:56 AM.

当我转换day.js通过dayjs.utc('2020-04-22T14:56:09.388842').local().format('MM/DD/YY h:mm A'),我得到的04/22/20 2:56 PM; 我正在导入 utc 插件。

我在 jsfiddle 中放了一个例子:https ://jsfiddle.net/obdg74sp/2/

有没有人遇到过这个问题,如果你遇到过,你是如何解决的?

谢谢你。

小智 11

我用了:

dayjs(date).utc('z').local().tz(ianaCode).format('ddd, MMM D, H:mm z')

例子:

dayjs('2021-06-08T24:00:00').utc('z').local().tz('America/Detroit').format('ddd, MMM D, H:mm z')


Mat*_*int 7

Moment 和 Day.js 都仅支持毫秒精度,但是当传入超过 3 位小数进行解析时,它们的行为有所不同。

  • Moment 会忽略多余的小数,但仍会使用自己的解析逻辑
  • Day.js 恢复到Date.parse函数

在后一种情况下,没有 UTC 感知,因此尽管通过dayjs.utc函数传递,您仍会获得本地时间。

这是在Day.js 问题 #544 中提出的,并由该库的所有者关闭,没有任何更改。

您可以通过修剪字符串以截断额外的小数来解决此问题。

dayjs.utc('2020-04-22T14:56:09.388842'.substring(0, 23))
Run Code Online (Sandbox Code Playgroud)

然后它将正确解析 UTC,您的其余逻辑将相应地工作。

(或者,您可以将 a 附加Z到字符串中)