1

I'm creating dates from strings with the format 'yyyy-MM-dd' but they're always created on the previous day for some reason. If I set the date as '2012-10-31' the Date object with actually be 30 of October and not 31. For example, this:

var d1=new Date('2012-10-31');

Will output this:

Tue Oct 30 2012 19:30:00 GMT-0430 (Venezuela Standard Time)

Can someone explain why this happens?

8vius
  • 5,786
  • 14
  • 74
  • 136

3 Answers3

1

Try this

var d1=new Date(2012, 10-1, 31, 0, 0 ,0);
document.write(d1);

which produces

Wed Oct 31 2012 00:00:00 GMT-0400 (Eastern Daylight Time) 

the key is to remove the quotes and manually set the time. Also note that 'month' is zero based and so for readability I subtract one from it

Eonasdan
  • 7,563
  • 8
  • 55
  • 82
  • I see the problem now, since the date isn't getting created with any time information is just takes it as GMT 0000 and rolls it back to my timezone. – 8vius Oct 31 '12 at 13:47
1

This happens because dates are converted to a string based on your local time zone.

The date variable actually contains October 31st 0:00 UTC. When you convert it to string, it is converted using your own time-zone, which is 4:30 hours behind UTC.

zmbq
  • 38,013
  • 14
  • 101
  • 171
1

With no further parameters, Date() create your time-stamp with GMT+0000.

Converting your date to string with no further parameters either, it will use the localised notation.
If you want to create a date matching your time-zone, do:

var d1=new Date('2012-10-31 GMT-0430');
//That's what you should get
//"Wed Oct 31 2012 00:00:00 GMT-0430"

Using this date now, you can convert the local time to the time of other timezones if you execute d1.toString() in a browser with a different timezone:

d1.toString();
//That's what I get
//"Wed Oct 31 2012 05:30:00 GMT+0100"
Nippey
  • 4,708
  • 36
  • 44