I'm pulling dates from a SQL database which treats them as dates that start at midnight. When I go to use toLocaleDateString()
on them, it formats them properly, however not before losing a day.
Before formatting: 2011-09-01T00:00:00
After formatting: 8/31/2011
Code:
plan.dateReceived = new Date(plan.dateReceived).toLocaleDateString()+','+plan.dateReceived;
Why does it do this, and what inline fix can I make to have it behave properly? I also found another post that had a similar problem, but I'm not 100% convinced that it's a timezone issue.
If you run the code in pieces, you'll notice that new Date('2011-09-01T00:00:00')
produces output like Wed Aug 31 2011 20:00:00 GMT-0400 (EDT)
(my computer is in EDT right now).
This is because (doc):
Differences in assumed time zone
Given a date string of "March 7, 2014", parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC. Therefore Date objects produced using those strings will represent different moments in time unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted (this behavior is changed in ECMAScript ed 6 so that both will be treated as local).
Converting that to the locale date string will convert it to a string appropriate for the browser's locale. Documentation indicates that "the default is the runtime's default time zone".
If you want to ensure the string is in UTC time, use
new Date('2011-09-01T00:00:00').toLocaleDateString('en-US', {timeZone: 'UTC'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With