4

I have built an application that is using pure javascript Date objects and date-fns for formatting and manipulating the objects.

The application functions perfectly in GMT where I developed it however I'm now on the West Coast of The States and I've discovered that many of my date objects are thrown out because of the timezone difference.

I am creating date objects from strings, either just YYYY-MM-DD or YYYY-MM-DD HH:mm, for example new Date('2018-01-19') or new Date('2018-01-19 08:00').

The issue is that when I create a date from a string of the format YYYY-MM-DD it creates the object disregarding the local timezone.

const date1 = new Date('2018-01-19');
const date2 = new Date('2018-01-19 00:00');

const dateString1 = format(date1, 'YYYY-MM-DD');     // gives '2018-01-18'
const dateString2 = format(date2, 'YYYY-MM-DD');     // gives '2018-01-19'

The behaviour is not consistent depending on whether you pass a time or not. If you pass a time then the date object is fixed to the local timezone, but if you don't then it is fixed to UTC. What I would like is that if I pass a datestring without the time (just year, month and day) that it would also create a date object assuming that it would be the start of the day in the local timezone.

Why is this? And do I just have to set the time as 00:00 each time I create a Date object?

1

1 Answer 1

1

"Why is this?"

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."

Parsing dates from strings isn't really advised; the recommendation is to do it manually by splitting the string and using the individual components as parameters. Or use a date library.

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

1 Comment

Sweet. Thanks for that. I wonder why they decided on this? It's not consistent behaviour... Anyway, I have created a little helper function that I pass the date string to when creating date objects and it simply tacks on a 00:00 on the end of the string if required: return new Date(dateString.length > 10 ? dateString : ${dateString} 00:00). Seems to be doing the trick :-)

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.