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?