简体   繁体   中英

JSON parse date and time?

Im having a little issue with parsing json date.

Here is what I would like to parse:

 {"driver": "247","firstName": "XXXXX","lastName": "XXXXX","lastLatitudeUpdate": "5/21/2012     4:49:17 PM","suspended": "false","checkedin": "0"}

I am having trouble parsing "lastLatitudeUpdate" is it because there are spaces in between? Thanks in advance for the help.

Short answer: No, there is no way for the JSON engine to recognize a string as a Date object.

Long answer: There is no 'date' type in JSON. However, this JSON is fine, the catch is that lastLatitudeUpdate will be parsed as a string. In order to convert this to a date you should try something like

var my_object= JSON.parse({"driver": "247","firstName": "XXXXX","lastName": "XXXXX","lastLatitudeUpdate": "5/21/2012     4:49:17 PM","suspended": "false","checkedin": "0"});
my_object.lastLatitudeUpdate= Date.parse(my_object.lastLatitudeUpdate)

This function will give a timestamp. However, you have to make sure the string is correctly recognized, you may have to do some extra work.

Assuming you are on Android and therefore working with java (yes you don't mention that, only the tag in your question suggests it...)

Like mentioned here (and in various other places) you can parse a date in java using the SimpleDateFormat class:

SimpleDateFormat parserSDF=new SimpleDateFormat("M/d/yyyy h:m:s a");
Date d = parserSDF.parse(dateField,0);

Of course you have to first parse you json input with some library (eg standard library from json.org or Google gson ) and then parse the string you'll get there for the field into a date.

How are you parsing the date? In Chrome this seems to work fine:

new Date("5/21/2012     4:49:17 PM");
Mon May 21 2012 16:49:17 GMT-0400 (US Eastern Daylight Time)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM