[英]Date.UTC() returns last day of previous month while getUTCFullYear(), getUTCMonth() returns correctly first day of correct month
我得到一个奇怪的结果:
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日,星期日,格林尼治标准时间-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));
此代码用于获取下个月的第一天(每月重复发生,直到下个月才能开始)。
然后您正在寻找
var today = new Date(); // now
var utcYear = today.getUTCMonth() < 11 ? today.getUTCFullYear() : today.getUTCFullYear() + 1;
var utcMonth = today.getUTCMonth() < 11 ? today.getUTCMonth() + 1 : 0;
var date = new Date(Date.UTC(utcYear, utcMonth)); // next UTC month
console.log(date.toString()); // Mon Jun 01 2015 02:00:00 GMT+0200
// or, in your timezone: Sun May 31 2015 19:00:00 GMT-0500 (same moment)
console.log(date.toUTCString()); // Mon, 01 Jun 2015 00:00:00 GMT
顺便说一句, Date
方法的确会将太大的值带入accout(并自动结转),因此您只需要执行
var today = new Date(); // now
var date = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth()+1)); // next UTC month
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.