Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Json date string to JavaScript date object

I have the following JSON object which has a date field in the following format:

{
    "AlertDate": "\/Date(1277334000000+0100)\/",
    "Progress": 1,
    "ReviewPeriod": 12 
}

I want to write a regular expression or a function to convert it to a javascript object so that it is in the form:

{
    "AlertDate": new Date(1277334000000),
    "Progress": 1,
    "ReviewPeriod": 12 
}

The above date format fails validation in the JQuery parseJSON method.

I would like to convert the 1277334000000+0100 into the correct number of milliseconds to create the correct date when eval is called after validation.

Can anyone help me out with a good approach to solving this?

like image 941
dagda1 Avatar asked Jun 22 '10 23:06

dagda1


People also ask

Does JSON Stringify convert date to UTC?

stringify converts DateTimeOffset to UTC format #1710.

Can JSON be a date?

JSON format does not have a special type for dates. So dates have to be represented in JSONs as numbers of milliseconds or as strings.

Is JSON Parsable JavaScript?

Parsing FunctionsFunctions are not allowed in JSON. If you need to include a function, write it as a string.

Is date object serializable JavaScript?

Date objects are serialized to ISO-formatted date strings (see the Date. toJSON() function), but JSON. parse() leaves these in string form and does not restore the original Date object. Function, RegExp, and Error objects and the undefined value cannot be serialized or restored.


1 Answers

Reusable jQuery extension that auto-parses dates

I've written a jQuery extension (in case you do use one and I hope/recommend you do) that changes $.parseJSON() functionality so it's able to automatically parse dates for you. No need for repetitious code for date parsing any more.

Check my blog post with code.

like image 181
Robert Koritnik Avatar answered Sep 22 '22 01:09

Robert Koritnik