Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is new Date() removing a day? - Javascript [duplicate]

I am creating a date with new Date(). When I do this, it is subtracting a day. Here is the code:

var dateString = "2016-04-10";
var date = new Date(dateString);

// date = Sat Apr 09 2016 18:00:00 GMT-0600 (MDT)

What do I misunderstand? Why is the date not Apr 10 2016? How do I make this work properly?

like image 883
jhamm Avatar asked Feb 08 '26 02:02

jhamm


1 Answers

Your timezone is GMT-6 (as revealed by the GMT-0600 (MDT) in the output you've provided). Therefore the date which gets generated is offset by -6 hours. In this case, midnight minus 6 hours is 6PM on the previous day.

If you call date.toISOString(), you'll see that the UTC time is "2016-04-10T00:00:00.000Z" as expected.

like image 124
James Donnelly Avatar answered Feb 09 '26 16:02

James Donnelly