caitlin
caitlin

Reputation: 2819

Converting JS array UNIX date integers into JS Date objects

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]
        ]
    },
]

Upvotes: 2

Views: 585

Answers (1)

Mike Lanzetta
Mike Lanzetta

Reputation: 361

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

Upvotes: 3

Related Questions