Converting .NET DateTime to JSON
Possible Duplicate:
How to format a JSON date?
My webs service is returning a DateTime to a jQuery call. The service returns the data in this format:
/Date(1245398693390)/
How can I convert this into a JavaScript-friendly date?
What is returned is milliseconds since epoch. You could do:
var d = new Date();
d.setTime(1245398693390);
document.write(d);
On how to format the date exactly as you want, see full Date
reference at http://www.w3schools.com/jsref/jsref_obj_date.asp
You could strip the non-digits by either parsing the integer (as suggested here):
var date = new Date(parseInt(jsonDate.substr(6)));
Or applying the following regular expression (from Tominator in the comments):
var jsonDate = jqueryCall(); // returns "/Date(1245398693390)/";
var re = /-?d+/;
var m = re.exec(jsonDate);
var d = new Date(parseInt(m[0]));
I have been using this method for a while:
using System;
public static class ExtensionMethods {
// returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
public static double UnixTicks(this DateTime dt)
{
DateTime d1 = new DateTime(1970, 1, 1);
DateTime d2 = dt.ToUniversalTime();
TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
return ts.TotalMilliseconds;
}
}
Assuming you are developing against .NET 3.5, it's a straight copy/paste. You can otherwise port it.
You can encapsulate this in a JSON object, or simply write it to the response stream.
On the Javascript/JSON side, you convert this to a date by simply passing the ticks into a new Date object:
jQuery.ajax({
...
success: function(msg) {
var d = new Date(msg);
}
}
使用带反向引用的String.replace解析日期字符串:
var milli = "/Date(1245398693390)/".replace(//Date((-?d+))//, '$1');
var d = new Date(parseInt(milli));
链接地址: http://www.djcxy.com/p/7998.html
上一篇: 如何从WCF服务中返回干净的JSON?