2015-05-09 54 views
0

我從Json的這樣2015-05-07T17:00:00Z解析字符串到日期戳的Java

我使用Eclipse構建Android應用

哪能其解析到日期的字符串?我不知道什麼是「T」和「Z」。

我通常會像這樣轉換日期..但是如何使用字符串「2015-05-07T17:00:00Z」?

或者我必須使用split來分割「 - 」,「T」,「:」和「Z」嗎?

Date today = new Date() 
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy") 
Date todayf = formatter.format(today) 
+1

檢查了這一點:http://stackoverflow.com/questions/4032967/json-date-to-java-date –

+0

使用「'T'」單引號爲T和Z是時區的含義UTC – redge

+1

I認爲你可以幫到你 http://stackoverflow.com/questions/8405087/what-is-this-date-format-2011-08-12t201746-384z – Simon

回答

1

讓我知道,如果下面的代碼爲你工作:

public static void main(String[] args) { 
     Date date = parseJSONDateTime("2015-05-07T17:00:00Z"); 
     System.out.println(date); 
    } 

    public static Date parseJSONDateTime(String jsonDateString) { 
     if (jsonDateString == null) return null; 
     SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ"); 
     if (jsonDateString.contains("T")) jsonDateString = jsonDateString.replace('T', ' '); 
     if (jsonDateString.contains("Z")) jsonDateString = jsonDateString.replace("Z", "+0000"); 
     else 
      jsonDateString = jsonDateString.substring(0, jsonDateString.lastIndexOf(':')) + jsonDateString.substring(jsonDateString.lastIndexOf(':')+1); 
     try { 
      return fmt.parse(jsonDateString); 
     } 
     catch (ParseException e) { 
      e.printStackTrace(); return null; 
     } 
    } 

此代碼將刪除T和替換Z+0000,然後相應地解析日期。

+0

太好了,謝謝 – akiong

1

Z是UTC時間。 T是用來分隔時間的文字,。如果你的字符串始終有一個「Z」,然後使用:

SimpleDateFormat formatter = new SimpleDateFormat(
    "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US); 
formatter.setTimeZone(TimeZone.getTimeZone("UTC")); 
Date todayf = formattter.format(today); 

更多here