Javascript Date and JSON DateTime
I have a problem with 开发者_C百科Jquery function getJSON, the action url does not trigger because one of the parameter i am passing is a javascript date but the action expects c# DateTime..
Is it possible to format the Javascript Date to make it compatible for c# DateTime?
I would suggest using the Datejs library (http://www.datejs.com/). From my limited experience with it it's fantastic.
Use this function taken from the Mozilla Date documentation:
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
.NET will have no problem handling an ISO formatted date. You can use DateTime.Parse(...)
to handle the ISO formatted string.
If you are trying for a solution to get a Javascript date from the JSON representation (/Date(1350035703817)/) you can use this function:
function parseJsonDate(jsonDate) {
var offset = new Date().getTimezoneOffset() * 60000;
var parts = /\/Date\((-?\d+)([+-]\d{2})?(\d{2})?.*/.exec(jsonDate);
if (parts[2] == undefined)
parts[2] = 0;
if (parts[3] == undefined)
parts[3] = 0;
return new Date(+parts[1] + offset + parts[2]*3600000 + parts[3]*60000);
};
Worked for me like charm.
I used this function, shorter than the above one.
function ParseJsonDate(dateString) {
var milli = dateString.replace(/\/Date\((-?\d+)\)\//, '$1');
var date = new Date(parseInt(milli));
return date;
}
Also found a method to convert them back:
function ToJsonDate(date) {
return '\/Date(' + date.getTime() + ')\/';
}
精彩评论