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.

10
  • Looks like a timezone problem. 4 hours difference, do you live on the East Coast? Commented Aug 22, 2012 at 17:25
  • see: stackoverflow.com/q/498578/220060 Commented Aug 22, 2012 at 17:25
  • @MikeRobinson yes I am in East Coast time zone Commented Aug 22, 2012 at 17:26
  • and also stackoverflow.com/q/4829569/220060 Commented Aug 22, 2012 at 17:27
  • 1
    Try new Date(selected.InspectionDate + "Z"). This fixes the timezone. But maybe this won't work on IE. Commented Aug 22, 2012 at 17:30

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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);

Comments

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());

1 Comment

This discards the time part. And why reinvent the wheel?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.