且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

您如何将毫秒转换为Javascript UTC日期?

更新时间:2023-01-16 09:27:28

如果已经是UTC日期的毫秒数.这基本上意味着世界时间.现在,基于这些毫秒数,您可以将Date对象转换为您喜欢的字符串:

If you have the milliseconds that's already the UTC date. Which basically means the universal time. Now based on those millis you can convert the Date object into a String of your like:


new Date(1446309338000).toUTCString() // timezone free universal format
> "Sat, 31 Oct 2015 16:35:38 GMT"
new Date(1446309338000).toString() // browser local timezon string
> "Sat Oct 31 2015 09:35:38 GMT-0700 (PDT)"
new Date(1446309338000).toISOString() // ISO format of the UTC time
> "2015-10-31T16:35:38.000Z"

现在,如果由于某种原因(我看不到正当的原因,只是出于某种原因),您正在寻找的毫秒数不同,代表的日期不同,但是在本地浏览器时区,您可以执行以下计算:

Now, if for some reason (I can't see a valid reason, but just for the heck of it) you're looking for having a different amount of milliseconds that represent a different date but that would print the same in the local browser timezone, you can do this calculation:


new Date(1446309338000 - new Date(1446309338000).getTimezoneOffset() * 60 * 1000))

现在,原始日期的toString和该新日期的toUTCString会读取相同的时区信息,因为它们当然不是同一日期!

Now toString from original Date and toUTCString of this new Date would read the same up to the Timezone information, because of course they're not the same date!


new Date(1446309338000).toString()
> "Sat Oct 31 2015 09:35:38 GMT-0700 (PDT)"
new Date(1446309338000 - new Date(1446309338000).getTimezoneOffset() * 60 * 1000).toUTCString()
> "Sat, 31 Oct 2015 09:35:38 GMT"