1

I really just have a simple question. I want to convert a string in yyyy-mm-dd to a date object in javascript. This seems simple enough. You can just do the following.

var date = new Date('2020-04-08');

But in this case, javascript considers the date '2020-04-08' as UTC midnight. So the actual date that is returned to me is the following.

Tue Apr 07 2020 17:00:00 GMT-0700 (Pacific Daylight Time)

I know I can create a date in the following format

var date = new Date(2020, 3, 8);
Wed Apr 08 2020 00:00:00 GMT-0700 (Pacific Daylight Time)

But it looks like too much hassle to extract the year, month and date from the already nicely formatted date string. Isn't there a simple way to convert yyyy-mm-dd string to a date object without it being treated as UTC date?

So in the simplest terms, my question is how do I tell the date constructor that the date I am passing is not a UTC date but a local date.

Ankur Patel
  • 1,413
  • 8
  • 14

1 Answers1

2

Simply append 'T00:00:00' to your date string.

const dateString = '2020-04-08'
const timeString = 'T00:00:00'

const date = new Date(dateString + timeString);
console.info(date.toString())

From the documentation

Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • Thank you very much for the response. I actually read this exact line before posting the question but I guess it didn't occur to me that just appending 'T00:00:00' will actually make the Date constructor treat the date as local. I think the documentation should be updated to something like the following. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local. If you don't want the '1970-01-01' to be treated as UTC then just append 'T00:00:00' to your date string. – Ankur Patel Apr 30 '20 at 05:08
  • 1
    Fails in Safari, which treats it as UTC regardless. The built–in parser should be avoided if at all possible, strings should be manually parsed with a function or library. If a library is used, the format should always be supplied. Also see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Apr 30 '20 at 06:11
  • Ah, curse you Safari! I always though ISO 8601 was safe with the `Date` constructor – Phil Apr 30 '20 at 06:47