1

Possible Duplicate:
Help parsing ISO 8601 date in Javascript

I think this should be very simple but turned out amazingly tedious.

From WEB API, I received selected object via ajax, and one of its properties is InspectionDate datetime string such as 2012-05-14T00:00:00

In javascript, I use following code to have correct date object

selected.JsInspectionDate = new Date(selected.InspectionDate);

But JsInspectionDate shows

2012/05/14 00:00 in firefox, 
2012/05/13 20:00 in chrome and 
NAN in IE9

for 2012-05-14T00:00:00.

Could someone tell me why this problem occurs? And how to fix this issue? I just want to show as in firefox for all browsers.

Community
  • 1
  • 1
Tae-Sung Shin
  • 20,215
  • 33
  • 138
  • 240

3 Answers3

2

Do this:

new Date(selected.InspectionDate + "Z")

Rationale: Your dates are in ISO 8601 form. Timezone designators like "Z", a very short one for UTC, work.

Note! IE might not understand ISO 8601 dates. All bets are off. In this case, better use datejs.

nalply
  • 26,770
  • 15
  • 78
  • 101
  • Yeah datejs was way to go. Everything is in harmony now. To be honest, I didn't know datejs was requirement. Thanks for your answer. – Tae-Sung Shin Aug 22 '12 at 17:49
1

Update:

First as one suggested, I tried following after referencing date.js.

selected.JsInspectionDate = Date.parse(selected.InspectionDate);

It seemed like working but later I found it was not enough since the JSON date string can have a format of 2012-05-14T00:00:00.0539 which date.js can't process either.

So my solution was

function dateParse(str) {
    var arr = str.split('.');
    return Date.parse(arr[0]);
}
...
selected.JsInspectionDate = dateParse(selected.InspectionDate);
Tae-Sung Shin
  • 20,215
  • 33
  • 138
  • 240
0

FIDDLE

var selectedDate='2012-05-14T00:00:00';
var formatttedDate=new Date(selectedDate.substr(0,selectedDate.indexOf('T')));

document.write(formatttedDate.getFullYear()+'/'+(formatttedDate.getMonth()<10?'0'+formatttedDate.getMonth():formatttedDate.getMonth())+'/'+formatttedDate.getDay());
Ashirvad
  • 2,367
  • 1
  • 16
  • 20