Scott Klarenbach
Scott Klarenbach

Reputation: 38721

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.

Upvotes: 6

Views: 3315

Answers (5)

cuixiping
cuixiping

Reputation: 25381

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);

Upvotes: 0

Robert Koritnik
Robert Koritnik

Reputation: 105029

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.

Upvotes: 1

ChaosPandion
ChaosPandion

Reputation: 78262

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

Upvotes: 5

moi_meme
moi_meme

Reputation: 9318

see Stand-Alone JSON Serialization on msdn which gives doc on MS implementation

Upvotes: 1

Matthew Flaschen
Matthew Flaschen

Reputation: 284806

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

Upvotes: 1

Related Questions