我也遇到这样的问题。 我想在给定日期元素的情况下设置 UTC 格式的日期。 日期为 UTC 时间 2017 年 10 月 31 日 如果我这样做:
var d1 = new Date();
d1.setUTCMilliseconds(0);
d1.setUTCSeconds(0);
d1.setUTCMinutes(0);
d1.setUTCHours(0);
d1.setUTCDate(31);
d1.setUTCMonth(9); //9 is october
d1.setUTCFullYear(2017);
console.log(d1);
控制台打印的日期是: 2017-10-01T00:00:00.000Z 这是十月一号。所有其他日子都按预期工作,但不是该月的最后一天。 这是一个错误还是有什么我不知道的事情?我只是 Javascript 的初学者。 谢谢
最佳答案
问题在于您设置字段的顺序。对于每个字段,Date
对象都会尝试使您的数字正常工作。由于大多数月份没有 31 天,因此 Date
此时的月份决定了它对 31 值的处理方式。例如,当我写这篇文章时,现在是 11 月,因此 new Date
为我们提供了 11 月的日期。调用 setDate(31)
会将日期设置为 12 月 1 日,因为即使 11 月只有 30 天,Date
对象也会尝试使 31 生效。如果当前是非闰年的 2 月,setDate(31)
会将日期设置为 3 月 3 日。
相反,请使用 new Date
和 Date.UTC
:
var d1 = new Date(Date.UTC(2017, 9, 31)); // All the others will default to 0
实例:
// Your way
var d1 = new Date();
d1.setUTCMilliseconds(0);
d1.setUTCSeconds(0);
d1.setUTCMinutes(0);
d1.setUTCHours(0);
d1.setUTCDate(31);
d1.setUTCMonth(9); //9 is october
d1.setUTCFullYear(2017);
console.log("Your way:");
console.log(d1.toISOString());
// Using new Date(Date.UTC(...)) instead:
d1 = new Date(Date.UTC(2017, 9, 31));
console.log("Using new Date(Date.UTC(...)) instead:");
console.log(d1.toISOString());
如果您出于某种原因不得不对单个调用执行此操作,您需要将月份设置为 1(因为,正如您在评论中所说,如果它只是恰好是 31,将月份设置为 11 月将导致 12 月 1 日!),然后按最大单位到最小单位的顺序设置字段:年、月、日、时、分、秒、毫秒:
d1 = new Date();
d1.setUTCDate(1);
d1.setUTCFullYear(2017);
d1.setUTCMonth(9); //9 is october
// ...and so on in order largest unit to smallest unit
实例:
// Setting them in order: Year, month, day, hour, minute, second, ms
var d1 = new Date();
d1.setUTCDate(1);
d1.setUTCFullYear(2017);
d1.setUTCMonth(9); //9 is october
d1.setUTCDate(31);
d1.setUTCHours(0);
d1.setUTCMinutes(0);
d1.setUTCSeconds(0);
d1.setUTCMilliseconds(0);
console.log("Setting them in order: Year, month, day, hour, minute, second, ms:");
console.log(d1.toISOString());
关于javascript - 在 Javascript 中设置 UTC 格式的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47050623/