Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse json date string in android

I get a json string with number of milliseconds after 1970 from the server in my android app.

Looks like this: \/Date(1358157378910+0100)\/.

How can I parse this into a Java calendar object, or just get some date value from it? Should I start with regex and just get the millisecons? The server is .NET.

Thanks

like image 998
PaperThick Avatar asked Jan 14 '13 10:01

PaperThick


2 Answers

The time seems to also have the timezone there so I would do something like this:

String timeString = json.substring(json.indexOf("(") + 1, json.indexOf(")"));
String[] timeSegments = timeString.split("\\+");
// May have to handle negative timezones
int timeZoneOffSet = Integer.valueOf(timeSegments[1]) * 36000; // (("0100" / 100) * 3600 * 1000)
int millis = Integer.valueOf(timeSegments[0]);
Date time = new Date(millis + timeZoneOffSet);
like image 141
pablisco Avatar answered Oct 09 '22 02:10

pablisco


Copied from the accepted answer, fixed some bugs :)

    String json = "Date(1358157378910+0100)";
    String timeString = json.substring(json.indexOf("(") + 1, json.indexOf(")"));
    String[] timeSegments = timeString.split("\\+");
    // May have to handle negative timezones
    int timeZoneOffSet = Integer.valueOf(timeSegments[1]) * 36000; // (("0100" / 100) * 3600 * 1000)
    long millis = Long.valueOf(timeSegments[0]);
    Date time = new Date(millis + timeZoneOffSet);
    System.out.println(time);
like image 43
thanhbinh84 Avatar answered Oct 09 '22 04:10

thanhbinh84