Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how do I parse a date from json?

Status
Not open for further replies.

jmeckley

Programmer
Joined
Jul 15, 2002
Messages
5,269
Location
US
i'm finally getting serious about client side code. using jquery as my framework.

I have an ajax request returning json. all is great, except dates are strings (example [\/Date(1198904400000-0500)\/]), not dates. googling shows this is expected. what I haven't found is a way to parse the json string-date to a real date object.

how do I do this? surprisingly the jquery forum has not responded to my question? maybe because this isn't directly a jquery issue. ideally I would like to do this
Code:
var result = get_json_result();
var a_real_date_object = result.a_date.[COLOR=blue]to_date()[/color];
alert(a_real_date_object);

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
ok, that was relatively painless
Code:
    String.prototype.to_date = function() {
        var date_as_string = this;
        while (date_as_string.indexOf("/") > -1) {
            date_as_string = date_as_string.replace("/", "");
        }
        return eval(date_as_string);
    };
and it's usage
Code:
var result = get_json_result();
var a_real_date_object = result.a_date.to_date();
alert(a_real_date_object);

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
spoke too soon. I can get a date, but it's the current date an time, not the date/time of the string.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi

I would send the date as Unix time, then use it as parameter for [tt]Date[/tt]'s constructor.
JavaScript:
var a_real_date_object = new Date(result.a_unix_time*1000);

Feherke.
 
the json serialization is done for me using the NetwonJson library and MonoRail. here is my final result
Code:
[COLOR=green]//assumes the string is in the format xxxxxx000000000000[anything]
//this is used for parsing json dates which have the format /Date(0000000000000-0000)/[/color]
String.prototype.to_date = function() {
    var date_as_integer = eval(this.substr(6, 13));
    return new Date(date_as_integer);
};

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top