[英]JSON `date(…)` to `java.Util.Date` using `org.json`
我正在學習Java並編寫一個Android應用程序,它使用服務器傳遞的JSON對象。
除了約會之外,我一切都在工作。
我得到了其中一個
'SomeKey':'\/Date(1263798000000)\/'
我正在使用org.json.JSONObject
。
如何將SomeKey
轉換為java.Util.Date
?
這可能有所幫助:
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);
}
日期格式在JSON中不是標准格式,因此您需要選擇“如何通過”。 我認為你看到的價值是毫克。
在Java中:
System.out.println (new Date(1263798000000L));
// prints: Mon Jan 18 09:00:00 IST 2010
當然,這是我的時區,但無論如何,這是一個相當近的日期。
從Date構造函數的javadoc:
參數:
date - 自1970年1月1日00:00:00 GMT以來的毫秒數。
鏈接到這里的文檔 - > http://java.sun.com/javase/6/docs/api/java/util/Date.html#Date%28long%29
正如Yoni已經提到的,JSON沒有定義日期是什么,或者如何序列化日期。 看看你發布的JSON片段,看起來好像有人覺得有點太有創意,序列化這樣的日期。
這里要注意的重要事項是:對於任何JSON解析器,這只是一個字符串。 “日期(12345)”部分毫無意義。 你必須將自己解析為java.util.Date
,在這種情況下,這意味着剝離任何不是數字的東西,並使用數字(UNIX時間)來實例化java.util.Date
。
僅供記錄。 使用JSON傳遞日期的典型方法是
{'timestamp':1265231402}
或者更有可能
{'timestamp':'Wed, 03 Feb 2010 22:10:38 +0100'}
后一個例子是使用標准RFC-2822格式的當前時間戳(正如我寫的那樣),可以使用Java的日期實用程序輕松解析。 看看SimpleDateFormat如何解析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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.