-1

This statement:

const date = new Date( '2022-05-04' );

produces the following value:

date = Tue May 03 2022 17:00:00 GMT-0700 (MST)

What's up with that?

How do I correct this?

TIA

unpocoloco
  • 15
  • 1
  • 5
  • 2
    It prints the date according to your machines timezone. If you want UTC then use the available UTC methods – pilchard May 04 '22 at 20:52
  • it assumes the date is UTC. the value is adjusted for timezone -- notice it's at 5pm MST, which is 7 hours behind UTC `new Date('2022-05-04T00:00:00-0700')` returns wednesday may 4th – Jhecht May 04 '22 at 20:52
  • 1
    It creates a date-time in UTC time zone at 12 am (0 hours), and in your local time it is still the previous day. – tromgy May 04 '22 at 20:53
  • @Jhecht unless your machine is in Pacific time ;) – pilchard May 04 '22 at 20:55
  • How to fix this depends on the context. How is that date going to be used? –  May 04 '22 at 20:55
  • try `new Date( '2022-05-04' ).toISOString()` – bill.gates May 04 '22 at 20:56
  • It's a good question, but it has been asked many times. The JS Date object is a strange bird. Depending on how your date is formatted and instantiated, it may output either local time or UTC/GMT. This answer does a good job of explaining it: https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results#answer-20463521 – Josh May 04 '22 at 21:12
  • When I created my question, none of the listed suggestions for already-answered ones were relevant. – unpocoloco May 04 '22 at 21:29
  • Found this immediately by googling "js date one day off" [Is the Javascript date object always one day off?](https://stackoverflow.com/questions/7556591/is-the-javascript-date-object-always-one-day-off) –  May 04 '22 at 22:01

2 Answers2

-1

The function gives the date according to your system's timezone. If you want UTC you need to mention it explicitly. const date = new Date( '2022-05-04' ).toUTCString();

Similarly you can change to other timezones.

Sneha
  • 140
  • 6
-1

Adding the .toUTCString() method fixed it. Thanks!

unpocoloco
  • 15
  • 1
  • 5
  • Please don't use answers for comments. Your issue is that timestamps in the format YYYY-MM-DD are parsed as UTC but *toString* shows local. A more suitable solution is usually to parse the timestamp as local initially (which is consistent with ISO 8601). – RobG May 05 '22 at 02:10