Why am I getting different results from the Date objects below? I can't figure it out. Would you be able to explain what each of these corresponds to? Thanks!
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'));
I am getting different days,
> 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)
The correct date seems to be the last one. How would I make the first two formats give the last one?
3rd command
console.log(new Date('2019-06-27T01:41:36'));
Give you right result because It is ISO Dates https://www.w3schools.com/js/js_date_formats.asp
2nd command
console.log(new Date(2019, 06, 27, 01, 41, 36));
Give you result less than 1 month. Because in Date constructor JavaScript counts months from 0 to 11 ( https://www.w3schools.com/js/js_dates.asp ), so you need subtract month by 1 to receive right result
console.log(new Date(2019, 06 - 1, 27, 01, 41, 36));
1st command
console.log(new Date(Date.UTC(2019, 06, 27, 01, 41, 36)));
Reason for wrong month is the same with 2nd command, and UTC cause hour changed
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);
In new Date('2019-06-27T01:41:36');
date is passed in dateString
, where month start from index - 1. See - https://tools.ietf.org/html/rfc2822#page-14 , https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
the numeric day-of-month MUST be between 1 and the number of days
allowed for the specified month
// The date is passed in dateString, where months start from index - 1 const dt2 = new Date('2019-06-27T01:41:36'); console.log(dt2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.