简体   繁体   English

如何在创建JavaScript日期时指定时区?

[英]How do I specify the time zone when creating a JavaScript Date?

I have a countdown clock that is set to countdown to 8am on January 1, 2014. 我有一个倒计时时钟,设定为2014年1月1日上午8点倒计时。

I am using the following code to set the date: 我使用以下代码来设置日期:

var futureDate = new Date(2014, 0, 1, 8, 0, 0, 0);

This works but I would like to take it a step further and set it to a specific timezone. 这有效,但我想更进一步,并将其设置为特定的时区。 In my case UTC -7. 在我的情况下UTC -7。

I have read this answer which says to use: 我已经阅读了这个使用说明的答案

new Date(Date.UTC(year, month, day, hour, minute, second))

but what I am confused about is how I set the timezone to be UTC -7 and what I read online only leaves me more confused. 但我感到困惑的是我如何将时区设置为UTC -7,而我在线阅读的内容只会让我更加困惑。

Can someone explain how Date.UTC works and how do I set a timezone so my countdown clock is counting down based on the specified timezone? 有人可以解释Date.UTC如何工作以及如何设置时区,以便我的倒计时时钟根据指定的时区倒计时?

Note: Any answer must be client side only code. 注意:任何答案必须是仅客户端代码。

Can someone explain how Date.UTC works 有人可以解释Date.UTC的工作原理

Date.UTC creates a timevalue for the provided year, month, date, etc. without any offset. Date.UTC为所提供的年,月,日等创建时间值,没有任何偏移。 So if the client machine is set for, say, UTC +05:00 then: 因此,如果客户端计算机设置为UTC +05:00,则:

var d = new Date(Date.UTC(2013, 11, 30, 12, 0, 0));

will create a date equivalent to noon on 30 December 2013 at Greenwich. 将于2013年12月30日在格林威治创建相当于中午的日期。 Alerting the date will print a local time (assuming +5:00) equivalent to 2013-12-30T17:00:00+05:00. 提醒日期将打印相当于2013-12-30T17:00:00 + 05:00的当地时间(假设+5:00)。

and how do I set a timezone so my countdown clock is counting down based on the specified timezone? 以及如何设置时区以使我的倒计时时钟根据指定的时区倒计时?

You can't set the timezone, however you can use UTC values to create a date object, adjust the hours and minutes for the offset, then use the UTC methods to get the date and time components for the countdown. 您无法设置时区,但是您可以使用UTC值创建日期对象,调整偏移的小时和分钟,然后使用UTC方法获取倒计时的日期和时间组件。

eg 例如

function z(n){return (n < 10? '0' : '') + n;}

var d = new Date(Date.UTC(2012, 11, 30, 12, 0, 0));

d.setUTCHours(d.getUTCHours() - 7);

alert(d.getUTCFullYear() + '-' + z(d.getUTCMonth() + 1) + '-' + 
      z(d.getUTCDate()) + 'T' + z(d.getUTCHours()) + ':' +
      z(d.getUTCMinutes()) + ':' + z(d.getUTCSeconds()) + '-07:00'
);

// 2012-12-30T05:00:00-07:00

If non–UTC methods are used, the local offset will affect the result. 如果使用非UTC方法,则本地偏移将影响结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM