Converting json results to a date

Possible Duplicate:
How to format a JSON date?

I have the following result from a $getJSON call from JavaScript. How do I convert the start property to a proper date in JavaScript?

[ {"id":1,"start":"/Date(1238540400000)/"}, {"id":2,"start":"/Date(1238626800000)/"} ]

Thanks!


You need to extract the number from the string, and pass it into the Date constructor :

var x = [{
    "id": 1,
    "start": "/Date(1238540400000)/"
}, {
    "id": 2,
    "start": "/Date(1238626800000)/"
}];

var myDate = new Date(x[0].start.match(/d+/)[0] * 1);

The parts are:

x[0].start                                - get the string from the JSON
x[0].start.match(/d+/)[0]                - extract the numeric part
x[0].start.match(/d+/)[0] * 1            - convert it to a numeric type
new Date(x[0].start.match(/d+/)[0] * 1)) - Create a date object

我使用这个:

function parseJsonDate(jsonDateString){
    return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}

If you use jQuery

In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON() function to automatically convert dates for you.

You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON() , but if you start using $.parseJSON(data, true) , dates in data string will be automatically converted to Javascript dates.

It supports Asp.net date strings: /Date(2934612301)/ as well as ISO strings 2010-01-01T12_34_56-789Z . The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).

Anyway. Head over to blog post to get the code. http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html

链接地址: http://www.djcxy.com/p/8148.html

上一篇: 如何使用JSON.NET通过ASP.NET MVC传递JSON日期值?

下一篇: 将json结果转换为日期