我得到了一个奇怪的结果:
var date = new Date();
var year = date.getMonth() < 11 ? date.getFullYear() : date.getFullYear() + 1;
var month = date.getMonth() < 11 ? date.getMonth() + 1 : 0;
console.log(new Date(Date.UTC(year, month)));
var utcYear = date.getUTCMonth() < 11 ? date.getUTCFullYear() : date.getUTCFullYear() + 1;
var utcMonth = date.getUTCMonth() < 11 ? date.getUTCMonth() + 1 : 0;
console.log(new Date(utcYear, utcMonth));
对于我正在使用的特定日期(任何日期都可以),Date.UTC 给我:
2015 年 5 月 31 日星期日 19:00:00 GMT-0500(中部夏令时间)
getUTC... 方法给了我:
2015 年 6 月 1 日星期一 00:00:00 GMT-0500(中部夏令时间)
我是否误用了 Date.UTC 或者我遗漏了什么?
谢谢
最佳答案
您正在使用 UTC 时间创建一个日期,但随后您以本地时间显示它,这就是为什么它晚了几个小时。使用Date.prototype.toUTCString()查看 UTC 时间
var date = new Date();
var year = date.getMonth() < 11 ? date.getFullYear() : date.getFullYear() + 1;
var month = date.getMonth() < 11 ? date.getMonth() + 1 : 0;
// It's a UTC date, display it as UTC, not local time
console.log(new Date(Date.UTC(year, month)).toUTCString());
var utcYear = date.getUTCMonth() < 11 ? date.getUTCFullYear() : date.getUTCFullYear() + 1;
var utcMonth = date.getUTCMonth() < 11 ? date.getUTCMonth() + 1 : 0;
// Created using local time, you can just use the normal toString()
console.log(new Date(utcYear, utcMonth));
关于javascript - Date.UTC() 返回上个月的最后一天,而 getUTCFullYear()、getUTCMonth() 正确返回正确月份的第一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30063445/