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
?
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);
}
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
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.
public String FormartDate(String date) {
Calendar calendar = Calendar.getInstance();
String datereip = date.replace("/Date(", "").replace(")/", "");
Long timeInMillis = Long.valueOf(datereip);
calendar.setTimeInMillis(timeInMillis);
String DateFmtI;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
DateFmtI = simpleDateFormat.format(calendar.getTime());
return DateFmtI;
}
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.