创建具有CET时区的Date对象 [英] Create a Date object with CET timezone

查看:54
本文介绍了创建具有CET时区的Date对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要在UTC中创建Date对象,我们要编写

To create Date object in UTC, we would write

new Date(Date.UTC(2012,02,30));

没有Date.UTC,它将采用 locale ,并创建 Date 对象.如果必须为在世界各地运行该程序的 CET 创建Date对象,该怎么办?

Without Date.UTC, it takes the locale and creates the Date object. If I have to create a Date object for CET running the program in some part of the world, how would I do it?

推荐答案

您不会在任何特定时区创建" JavaScript Date 对象.JavaScript Date 对象始终从毫秒数UTC值开始工作.它们具有应用本地时区偏移量和规则( getHours 而不是 getUTCHours )的方法,但是仅应用本地时区.您无法设置对象 Date 用于其本地"方法的时区.

You don't create a JavaScript Date object "in" any specific timezone. JavaScript Date objects always work from a milliseconds-since-the-Epoch UTC value. They have methods that apply the local timezone offset and rules (getHours as opposed to getUTCHours), but only the local timezone. You can't set the timezone the Date object uses for its "local" methods.

您对 Date.UTC 所做的操作(正确的是,除了 02 上领先的 0 之外)只是使用UTC中该日期/时间(3月30日午夜)的相应毫秒值,因为自Epoch,而 new Date(2012,2,30)会将其解释为3月30日午夜当地时间.除了初始日期时间以外, Date 对象中的没有差异.

What you're doing with Date.UTC (correctly, other than the leading 0 on 02) is just initializing the object with the appropriate milliseconds-since-the-Epoch value for that date/time (March 30th at midnight) in UTC, whereas new Date(2012, 2, 30) would have interpreted it as March 30th at midnight local time. There is no difference in the Date object other than the datetime it was initialized with.

如果您需要的不是本地时区,则可以使用 Date 函数的UTC版本,并为要使用的时区应用自己的偏移量和规则,即不平凡的.(偏移量是微不足道的;规则并非如此.)

If you need a timezone other than local, all you can do is use the UTC version of Date's functions and apply your own offset and rules for the timezone you want to use, which is non-trivial. (The offset is trivial; the rules tend not to be.)

如果您继续寻找,可以找到可以为您处理时区的Node模块.现在,快速搜索节点时区"给了我 时区 作为第一击.它还给了我此SO问题

If you go looking, you can find Node modules that handle timezones for you. A quick search for "node timezone" just now gave me timezone as the first hit. It also gave me links to this SO question, this SO question, and this list of timezone modules for Node.

这篇关于创建具有CET时区的Date对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆