2

Is there a way to convert UNIX epoch integers (1402079444, etc) in an array into JavaScript Date objects (Date.UTC(2014, 9, 14), etc) using jQuery?

I'm trying to pass a large JSON array generated by PHP to Highmaps.JS, which almost works great however Highmaps expects a Date object and Date objects aren't valid JSON, so I can't generate them with PHP.

jsFiddle of my current setup here: http://jsfiddle.net/dwgLtscm/2/

(The x-axis isn't displaying dates properly because the data isn't in the proper date format).

[{
    "name": "Dissolved Oxygen",
    "data": [
            [1402079444,9]
        ]
    },
    {
        "name": "Temperature (Water)",
        "data": [
            [1401291099,9],
            [1401862547,12]
        ]
    },
    {
        "name": "Temperature (Air)",
        "data": [
            [1401291099,13],
            [1401862547,19]
        ]
    },
]

1 Answer 1

3

Given the Json object above, I'd try:

array.forEach(function (val) { 
  val.data = val.data.map(function (datum) {
    return [ new Date(datum[0] * 1000), datum[1] ];
  }
}

Unless I'm reading it wrong (I'm assuming data[0] is the UTC value).

(Edited based on feedback below, thanks all!)

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

4 Comments

Hm, that didn't quite work- it seemed to wipe out the data array. I added a jsFiddle so you can see what's going on!
Better multiply unix timestamp by 1000 to get new Date in javascript
You can pass the seconds * 1000 into the Date constructor and you probably meant to use map instead of forEach in the inner call. Right now your return value is being ignored
Thanks! Good call - I was running out the door so didn't have time to test it :-\

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.