new Date('2019-01-01')
Mon Dec 31 2018 19:00:00 GMT-0500 (Eastern Standard Time)
new Date('2019-01-01').getDate()
31
I would be expecting 1 to be the result. How can I get day relative to current timezone using Date in Javascript?
new Date('2019-01-01')
Mon Dec 31 2018 19:00:00 GMT-0500 (Eastern Standard Time)
new Date('2019-01-01').getDate()
31
I would be expecting 1 to be the result. How can I get day relative to current timezone using Date in Javascript?
The constructor appears to set the Date object's value using the UTC time that corresponds to the string argument (midnight on 2019-01-01) -- for which the local equivalent is Mon Dec 31 2018 19:00:00 GMT-0500 (Eastern Standard Time)
.
Storing local midnight would mean actually storing 5AM UTC, like:
new Date('2019-01-01T05:00:00');
Since we don't necessarily know the difference between local and UTC times in advance, we can find and use it dynamically like this:
let date = new Date("2019-01-01");
let offset = date.getTimezoneOffset(); // Returns the offset in minutes
date = new Date(date.getTime() + (offset * 60 * 1000)); // Adds the offset in milliseconds
console.log(date.toLocaleString());
For further reference,
- Here's a somewhat-related question (where the top answer actually recommends importing a library to handle these issues): How to add 30 minutes to a JavaScript Date object?,
- And here's good-ol' MDN's page on JS dates:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
If you populate the Date
constructor with the timezone offset, you can instead use getUTCDate
.
var date1 = new Date('August 19, 1975 23:15:30 GMT+11:00');
var date2 = new Date('August 19, 1975 23:15:30 GMT-11:00');
console.log(date1.getUTCDate());
// expected output: 19
console.log(date2.getUTCDate());
// expected output: 20