1

consider the following simple javascript code example below. I would expect same values for d and x, e.g. d-x = 0, but that does not seem to be the case? Am I not allowed to use the date string format used for var x, or is there another reason? (I could not directly find such restriction in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse, but also not an example with the string format yyyy-mm-dd)

var d = Date.parse("March 21, 2012"); 

alert(d); //val 1332284400000

var x = Date.parse("2012-03-21");

alert(x);  //val 1332288000000

alert(d-x); //val -3600000
Joppo
  • 715
  • 2
  • 12
  • 31

2 Answers2

1

If a recent browser can interpret as date string as ISO-8601 - it will(!!!). With this format, your date/time string is interpreted as UTC(!!!)

You should Stick to "YYYY/MM/DD" for your date strings whenever possible. It's universally supported and unambiguous. With this format, all times are local.

For example : look at this mess :

new Date("2013-07-27T10:10:10")

chrome : Sat Jul 27 2013 13:10:10 GMT+0300 (Jerusalem Daylight Time)
ff:      Sat Jul 27 2013 10:10:10 GMT+0300 (Jerusalem Standard Time)
ie8  : nan
ie :     Sat Jul 27 10:10:10 UTC+0300 2013 

While :

new Date("2013/07/27 10:10:10")

ie:     Sat Jul 27 10:10:10 UTC+0300 2013 
chrome: Sat Jul 27 2013 10:10:10 GMT+0300 (Jerusalem Daylight Time)
ff:     Sat Jul 27 2013 10:10:10 GMT+0300 (Jerusalem Standard Time) 
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
0

I tried to print the date by alerting the date string, and found

var d = Date.parse("March 21, 2012"); 
var formatted_d = new Date(d);
alert(formatted_d); 

var x = Date.parse("2012-03-21");
var formatted_x = new Date(x);
alert(formatted_x); 

Wed Mar 21 2012 00:00:00 GMT+1100 (EST) and

Wed Mar 21 2012 11:00:00 GMT+1100 (EST)

So when parsing "March 21, 2012", the timezone is assumed as 0. But when parsing "2012-03-21", timezone is assumed as your browser timezone.

Ethan Fang
  • 1,271
  • 10
  • 15