Thursday, July 26, 2012

Dates, Time Zones, JSON and MVC

Ran into an issue with sending a date to MVC. Needed to have a date within a certain range, and I'm using a Telerik date picker to do the date selection. Worked great, here in California. Didn't work so well in India.

When you create a date in Javascript, it appends the time zone.

Sat Jan 01 2000 00:00:00 GMT-0800 (Pacific Standard Time)

When you send it via ajax, it's converted to UTC, or 

"2000-01-01T08:00:00.000Z"

This works fine for time zones with a negative UTC offset. For time with a positive offset, this can set their selection outside of the date range,

"
1999-12-31T18:30:00.000Z"

I think this could be a fix...

myDate = new Date("1/1/2000")
Sat Jan 01 2000 00:00:00 GMT-0800 (Pacific Standard Time)
myDate.setMinutes(-myDate.getTimezoneOffset())
946684800000
myDate
Fri Dec 31 1999 16:00:00 GMT-0800 (Pacific Standard Time)
myDate.toJSON()
"2000-01-01T00:00:00.000Z"

And with my time set to IST


var myDate = new Date("1/1/2000")
undefined
myDate
Sat Jan 01 2000 00:00:00 GMT+0530 (India Standard Time)
myDate.setMinutes(-myDate.getTimezoneOffset())
946684800000
myDate
Sat Jan 01 2000 05:30:00 GMT+0530 (India Standard Time)
myDate.toJSON()
"2000-01-01T00:00:00.000Z"

No comments:

Post a Comment