为什么我得到不同的日期结果

时间:2019-06-27 03:11:19

标签: javascript

为什么我从下面的Date对象得到不同的结果?我不知道。您能解释这些分别对应什么吗?谢谢!

console.log(new Date(Date.UTC(2019, 06, 27, 01, 41, 36)));
console.log(new Date(2019, 06, 27, 01, 41, 36));
console.log(new Date('2019-06-27T01:41:36'));

我日子不一样了

> Fri Jul 26 2019 19:41:36 GMT-0600 (Mountain Daylight Time)
> Sat Jul 27 2019 01:41:36 GMT-0600 (Mountain Daylight Time)
> Thu Jun 27 2019 01:41:36 GMT-0600 (Mountain Daylight Time)

正确的日期似乎是最后一个。我如何使前两种格式给出最后一种格式?

2 个答案:

答案 0 :(得分:3)

第三个命令

console.log(new Date('2019-06-27T01:41:36'));

为您提供正确的结果,因为它是ISO日期https://www.w3schools.com/js/js_date_formats.asp

第二个命令

console.log(new Date(2019, 06, 27, 01, 41, 36));

结果少于1个月。因为在Date构造函数中,JavaScript会将月份从0到11(https://www.w3schools.com/js/js_dates.asp)进行计数,所以您需要将月份减1才能得到正确的结果

console.log(new Date(2019, 06 - 1, 27, 01, 41, 36));

第一个命令

console.log(new Date(Date.UTC(2019, 06, 27, 01, 41, 36)));

错误月份的原因与第二条命令相同,并且UTC原因小时已更改

答案 1 :(得分:1)

const dt = new Date(Date.UTC(2019, 06, 27, 01, 41, 36));

// To display the date in UTC timezone use `toUTCString()`
// See - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/UTC
// Months start from index - 0
// 0 - Jan, 1-Feb, 2-Mar, 3-Apr, 4-May, 5-May, 6-Jun

console.log(dt.toUTCString());

// Individual date and time components are passed. 
// Month starts from index - 0
const dt1 = new Date(2019, 06, 27, 01, 41, 36);

console.log(dt1);

new Date('2019-06-27T01:41:36');中将日期传递到dateString中,其中月份从索引-1开始。请参见-https://tools.ietf.org/html/rfc2822#page-14https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

  

数字日期必须在1到天数之间
  在指定月份允许

// The date is passed in dateString, where months start from index - 1

const dt2 = new Date('2019-06-27T01:41:36');
console.log(dt2);