0

Let's say you have the following object as a string:

var timecard = {
  "name": "Joe",
  "time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)"
} 

// as string
var stringed = 'var timecard = {   "name": "Joe",   "time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)" }'

and you run JSON.parse(stringed) to parse it into the object. How would you go about having it convert the date into an actual Date object as opposed to a string?

Thanks!

1
  • I think the declaration and assignment of stringed should be JSON.stringify(timecard) Commented Apr 26, 2015 at 18:03

1 Answer 1

5

The JSON data format doesn't have a date type, so you have to write the code to transform it into a Date object yourself.

You can pass a reviver function as the second argument to JSON.parse to do that.

    function parseDate(k, v) {
      if (k === "time") {
        return new Date(v);
      }
      return v;
    }
    var json = '{   "name": "Joe",   "time": "Sun Apr 26 2015 13:58:54 GMT-0400 (EDT)" }';
    var data = JSON.parse(json, parseDate);
    console.log(data);

Sign up to request clarification or add additional context in comments.

2 Comments

What if you do not have the time variable name available? ie. its a JS library for parsing objects
@JimMarcus — Then you have to use some other method to determine which fields you want to convert to dates. e.g. you could write a "Looks like a date" regular expression, or try to convert everything to dates and see what is converted successfully.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.