2

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?

oldo.nicho
  • 2,149
  • 2
  • 25
  • 39
  • Does this answer your question? [Parse YYYY-MM-DD dates using the local timezone](https://stackoverflow.com/questions/17893896/parse-yyyy-mm-dd-dates-using-the-local-timezone) – Oswaldo Oct 07 '20 at 18:11

1 Answers1

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.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
  • 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 :-) – oldo.nicho Jan 20 '18 at 02:52