2

I get a date in string format that I use to create a new Date().

let date_str = '2019-09-08';
let date = new Date(date_str);
console.log(date);

When printed, instead of being 2019-09-08T00:00:00.000Z as expected, it seems that the date is converted to my timezone, and the console prints Sat Sep 07 2019 20:00:00 GMT-0400, which essentially changes the date and there functionality I need.

What is causing this and how can I get around this?

Note: I tried running the above code as a code snippet in this post, but got 2019-09-08T00:00:00.000Z instead of the erroneous date...

jpc
  • 129
  • 3
  • 16
  • 1
    `console.log(date.toUTCString())` — presentation of dates as strings is always local time by default. – Pointy Sep 07 '19 at 21:54

1 Answers1

3

That is the correct date, it's just displayed in your local timezone when you convert it to a string. Date objects internally just store a unix timestamp in milliseconds. They don't store any timezone information; timezone is only important when converting to/from a string. These two values are the same:

console.log( new Date( '2019-09-08' ).getTime( ) );
console.log( new Date( '2019-09-07T20:00:00.000-04:00' ).getTime( ) );

If you want to display a date object as a UTC ISO string, use Date#toISOString:

console.log( new Date( '2019-09-08' ).toISOString( ) );
console.log( new Date( '2019-09-07T20:00:00.000-04:00' ).toISOString( ) );
Paul
  • 139,544
  • 27
  • 275
  • 264