tags:

views:

807

answers:

2

Hey all.

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?

+4  A: 

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

Yoni
I'm new to ava as well, how do I do a regular expression to get the value?
Daniel A. White
You don't have to use regular expressions, you can use the String methods, to get a substring. Have a look at the docs.
Yoni
+1  A: 

As Yoni already mentioned, JSON does not define what a date is, or how to serialize one. Looking at the JSON snippet you posted, it looks as if someone felt a little too creative, serializing a date like that.

The important thing to note here is: to any JSON parser, this is just a string. The "Date(12345)" part is meaningless. You have to parse that yourself into a java.util.Date, which in that case means stripping off anything that's not a number, and using the number (the UNIX time) to instantiate a java.util.Date.

Just for the record. A typical way to pass a date using JSON would be either

{'timestamp':1265231402}

or more likely

{'timestamp':'Wed, 03 Feb 2010 22:10:38 +0100'}

The latter example would be the current timestamp (as I'm writing this) using standard RFC-2822 formatting, which can easily be parsed using Java's date utilities. Have a look at SimpleDateFormat for how to parse dates in Java.

Matthias