Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON date format for jquery ajax request

I want to load some data via ajax and have the dates parsed automatically.

var url = "http://example.com/report_containing_dates.json"
jQuery.getJSON(url, function(data_containing_dates_and_strings){
  console.log(date);
});

The date format in my json is "2012-09-28" (the default from rails to_json) but jQuery just treats this a string. What format does the date need to be in for jquery to parse it as a date?

Sample response:

{
  "columns": [
    ["date", "Date"],
    ["number", "active_users"],
  ],
  "rows": [
    ["2012-09-28", 120, 98, 60],
    ["2012-09-29", 127, 107, 63]
  ]
}
like image 275
opsb Avatar asked Oct 12 '12 13:10

opsb


2 Answers

It doesn't matter how you format the date string. JSON methods will never automatically convert it into an Date object. JSON only supports these basic types: Number, String, Boolean, Array, Object and null. (http://en.wikipedia.org/wiki/JSON)

You have to convert these date strings yourself into Date objects.

In your case that could be something like:

$.each(response.rows, function (idx, row) {

  row[0] = Date.parse(row[0]);
}
like image 55
lrsjng Avatar answered Nov 12 '22 13:11

lrsjng


Use Date.parse, that will convert from string to date.

like image 3
Riz Avatar answered Nov 12 '22 13:11

Riz