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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
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?
Ah, curse you Safari! I always though ISO 8601 was safe with the Date constructor

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.