Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON `date(...)` to `java.Util.Date` using `org.json`

Tags:

java

json

android

I'm learning Java and writing an android app that consumes a JSON object that is passed by the server.

I have it all working except the dates.

I get one of these back

'SomeKey':'\/Date(1263798000000)\/'

I am using org.json.JSONObject.

How do i convert SomeKey into a java.Util.Date?

like image 333
Daniel A. White Avatar asked Feb 03 '10 20:02

Daniel A. White


People also ask

How to Convert JSON date to java date?

By using Gson, we can generate JSON and convert JSON to java objects. We can create a Gson instance by creating a GsonBuilder instance and calling with the create() method. The GsonBuilder(). setDateFormat() method configures Gson to serialize Date objects according to the pattern provided.

How to format JSON string to date in java?

We can format a date using the setDateFormat() of ObjectMapper class. This method can be used for configuring the default DateFormat when serializing time values as Strings and deserializing from JSON Strings.

How to get date Object from JSON in java?

You may do like below, String dateStr = obj. getString("birthdate"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date birthDate = sdf. parse(dateStr); //then user.

How to pass date field in JSON?

JSON does not have a built-in type for date/time values. The general consensus is to store the date/time value as a string in ISO 8601 format.


2 Answers

This might help:

public static Date JsonDateToDate(String jsonDate)
{
    //  "/Date(1321867151710)/"
    int idx1 = jsonDate.indexOf("(");
    int idx2 = jsonDate.indexOf(")");
    String s = jsonDate.substring(idx1+1, idx2);
    long l = Long.valueOf(s);
    return new Date(l);
}
like image 196
Eyal Avatar answered Nov 02 '22 17:11

Eyal


Date format is not standard in JSON, so you need to choose how you "pass it through". I think the value you are seeing is in millis.

In Java:

System.out.println (new Date(1263798000000L));
// prints: Mon Jan 18 09:00:00 IST 2010

This is in my timezone, of course, but in any case it is a fairly recent date.

From the javadoc of the Date constructor:

Parameters:
date - the milliseconds since January 1, 1970, 00:00:00 GMT.

Link to the docs here -> http://java.sun.com/javase/6/docs/api/java/util/Date.html#Date%28long%29

like image 8
Yoni Avatar answered Nov 02 '22 18:11

Yoni