JavaScript 日期方法之间有什么区别吗:
setUTCminutes()
对比
setMinutes()
是否会使用 setMinutes()
将时区恢复为 UTC 以外的其他时间?
我正在考虑是否使用日期字符串设置 UTC 时间:
var dUTC = new Date('March 20, 2016 20:45:00 UTC');
或使用 UTC 方法设置日期,然后设置小时等:
var d = new Date(2016,3,20);
d.setUTCHours(20);
d.setUTCminutes(45);
但是,我担心第二种方法在某些情况下可能不准确。我不想以错误的 UTC 日期结束。我的插件可以在全世界使用。
最佳答案
Is there any difference between the JavaScript date methods:
setUTCminutes() versus
setMinutes()
是的。设置 UTCMinutes 将根据新的 UTC 分钟值调整内部时间值(即 UTC)。
setMinutes 做同样的事情,但会考虑内部时区,因此时间的变化可能会有所不同(因为许多时区不是完整的小时)。
例如对于 UTC+0030 的时区,如果本地时间是 01:00,则将 UTC 分钟设置为 30 不会执行任何操作(因为当前是 UTC 00:30),但是将本地分钟设置为 30 会将 UTC 分钟设置为 00:00
此外,如果新的分钟导致日期跨越夏令时边界,则新时间减去 UTC 和本地的旧时间可能会有所不同。
Will using setMinutes() revert the time zone back to something other than UTC?
没有。日期对象没有时区,主机系统有。日期对象使用 UTC 时间值,然后在计算中使用主机的时区,它不是日期本身的属性(因此方法 getTimezoneOffset) .
I'm contemplating whether to set the UTC time with a date string:
var dUTC = new Date('March 20, 2016 20:45:00 UTC');
不!不要那样做。强烈反对使用 Date 构造函数解析字符串(只需在此处搜索有关解析的问题数量)。该日期格式不受 ECMA-262 支持,因此解析完全取决于实现。时区可能会重新调整,也可能不会,或者您可能会得到无效的日期。
or set the date, then set the hour, etc with UTC methods:
var d = new Date(2016,20,3); d.setUTCHours(20); d.setUTCminutes(45);
But, I'm concerned that the second method might not be accurate in some situations.
传递给 Date 构造函数的值似乎不正确,值是年、月、日。也许你的意思是:
new Date(2016, 3, 20) // 20 April, 2016
在上面创建日期时,主机时区将影响用于创建 UTC 时间值的值。使用 UTC 方法设置时间很可能会导致意外结果,因此请不要那样做。
如果您想要在任何地方都能使用的东西,请始终使用 UTC,然后仅转换为“本地”以进行输出。所以如果你想创建一个基于 UTC 的日期和时间:
var d = new Date(Date.UTC(2016, 3, 20, 20, 45);
将为 2016-04-20T20:45:00Z 创建一个日期
关于javascript - setUTCminutes 与 setMinutes 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35712699/