简体   繁体   中英

JSON Parse Date Formats?

Am I correct in assuming that I have to MANUALLY convert Json-encoded date strings to date objects in my client code?

Coming from C#, I took for granted that this was happening automatically, but I guess that was .NET.

Is there a built in mechanism for getting native javascript types from a Json string (for dates, ints, etc.)?

Thanks.

The JSON spec does not define a date data type. That is left up to you.

See Section A.8: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf

JSON does not have a standard date type. There are various libraries (including .NET) with incompatible extensions for representing it.

请参阅msdn上的Stand-Alone JSON Serialization,它提供了有关MS实现的文档

Auto convert ISO and Asp.net dates date strings to dates

If you use any client-side library like jQuery, you can use my jQuery extension that makes it possible to automatically convert ISO dates and Asp.net dates to actual dates using $.parseJSON() .

Check my blog post for code.

JSON.parse() supports replacer param.

JSON.stringify(value[, replacer[, space]])

See details on MDN

So you can handle the date type easily in json.

function replacer(key, value) {
  return key == "date1" || key == "date2" ? new Date(value) : value;
}

var obj = {
    date1:"5/21/2012 4:49:17 PM",
    date2:new Date()
}
var jsonString = JSON.stringify(obj);
console.log(jsonString);
var jsonObj = JSON.parse(jsonString, replacer);
console.log(jsonObj);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM