0
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?

Logan
  • 10,649
  • 13
  • 41
  • 54
  • 2019-01-01 is parsed as UTC, to get the date just use `date.getUTCDate()` or `"2019-01-01".substr(8,2)` and avoid date parsing altogether. – RobG Jul 28 '19 at 10:53

2 Answers2

1

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

Cat
  • 4,141
  • 2
  • 10
  • 18
  • 2019-01-01 will be parsed as UTC, so simpler to just get the UTC date: `new Date("2019-01-01").getUTCDate()` returns 1. – RobG Jul 28 '19 at 10:54
0

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

GenericUser
  • 3,003
  • 1
  • 11
  • 17