JSON date format for jquery ajax request
Asked Answered
A

5

5

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]
  ]
}
Africa answered 12/10, 2012 at 13:7 Comment(0)
A
2

OK, that was much harder than expected but I do have a solution.

The approach I've taken is to ask for a custom datatype in the ajax request and then implement a custom converter.

First of all the format I'm using for dates in my json is now date("yyyy-mm-dd"), the original example would look like:

{
  "columns": [
    ["date", "Date"],
    ["number", "active_users"],
  ],
  "rows": [
    ["date(2012-09-28)", 120, 98, 60],
    ["date(2012-09-29)", 127, 107, 63]
  ]
}

I then register a converter to convert text to a custom datatype called json_with_dates. A regex is used to search for the date format and replace them with statements to create date objects. Eval is then used to construct the json.

jQuery.ajaxSetup({
  converters: {
    "text json_with_dates": function( text ) {

      var with_dates = text.replace(/\"date\(([^)]*)\)\"/g, function(a, date){
        var dateParts = date.split("-");
        return "new Date(" + dateParts[0] + "," + dateParts[1] + "," + dateParts[2] + ")";
      });

      var converted = eval("(" + with_dates + ")");
      return converted;
    }
  }
});

I then make the ajax request for the custom datatype:

$.ajax({
    url: div.data('chart'),
    dataType: 'json_with_dates',
    success: function(data_including_dates){
      console.log("win!");
    }
});
Africa answered 12/10, 2012 at 14:57 Comment(0)
I
6

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]);
}
Isoagglutination answered 12/10, 2012 at 13:23 Comment(0)
C
3

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

Carny answered 12/10, 2012 at 13:10 Comment(0)
A
2

OK, that was much harder than expected but I do have a solution.

The approach I've taken is to ask for a custom datatype in the ajax request and then implement a custom converter.

First of all the format I'm using for dates in my json is now date("yyyy-mm-dd"), the original example would look like:

{
  "columns": [
    ["date", "Date"],
    ["number", "active_users"],
  ],
  "rows": [
    ["date(2012-09-28)", 120, 98, 60],
    ["date(2012-09-29)", 127, 107, 63]
  ]
}

I then register a converter to convert text to a custom datatype called json_with_dates. A regex is used to search for the date format and replace them with statements to create date objects. Eval is then used to construct the json.

jQuery.ajaxSetup({
  converters: {
    "text json_with_dates": function( text ) {

      var with_dates = text.replace(/\"date\(([^)]*)\)\"/g, function(a, date){
        var dateParts = date.split("-");
        return "new Date(" + dateParts[0] + "," + dateParts[1] + "," + dateParts[2] + ")";
      });

      var converted = eval("(" + with_dates + ")");
      return converted;
    }
  }
});

I then make the ajax request for the custom datatype:

$.ajax({
    url: div.data('chart'),
    dataType: 'json_with_dates',
    success: function(data_including_dates){
      console.log("win!");
    }
});
Africa answered 12/10, 2012 at 14:57 Comment(0)
S
0

It may be best to parse the date yourself. I've ran across issues in certain browsers not parsing the date from a string as you would expect. Here's a quick prototype to use on the string 2012-09-28:

String.prototype.parseDate = function(){
     var date = this.split("-");
     var yyyy = date[0];
     var mm = date[1];
     var dd = date[2];

     date = new Date(yyyy,mm,dd);
     date.setMonth(date.getMonth()-1); // since Months are 0 based
     return date;
}

console.log(data.rows[0][0].parseDate());
console.log(data.rows[1][0].parseDate());​

EXAMPLE

Taken from a similar question: IE JavaScript date parsing error

The Date.parse method is completely implementation dependent (new Date(string) is equivalent to Date.parse(string))

Strobila answered 12/10, 2012 at 13:45 Comment(0)
C
0

when we are trying to read date time values from database using Ajax calling returned like this Value : /Date(1634564200000)/ and html table bind column value also showing like this. If you are replace some character then you can find solution.

var DOB= new Date(eval('new' + response.d[0].dob.replace(///g, ' '))); var Read_Date = DOB.getMonth() '/' + DOB.getDate() + '/' + SDate.getFullYear(); alert(Read_Date)

Comity answered 5/10, 2023 at 8:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.