2013-10-10 46 views
1

如何在有效的java日期中解析以下日期字符串?我在解析時區時遇到問題。Java中的時區解析問題

「2013年10月10日10時43分44秒GMT + 5」

我使用解析日期下面的方法。它運作良好時,時區是像「GMT + 05:00」,但無法解析,即使我使用Z,Z的不同組合上面的字符串,X

public static Date convertStringWithTimezoneToDate(String dateString) { 
     if (dateString == null) { 
      return null; 
     } 
     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzzz"); 
     Date convertedDate = null; 
     try { 
      convertedDate = dateFormat.parse(dateString); 
     } catch (ParseException e) { 
      e.printStackTrace(); 
     } 
     return convertedDate; 
    } 
+2

嘗試轉換GMT + 5 ==> GMT + 5:00。根據此 http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html#timezone – Reddy

+0

閱讀此[答案] [1]可能無效將有助於你 [1]:http://stackoverflow.com/questions/4496359/how-to-parse-date-string-to-date – Engineer

+0

請參考[this one](http:// stackoverflow。 com/questions/8035125/java-how-to-add-seconds-to-timestamp) –

回答

0

您的日期格式不規範。時區必須尊重在documentation給出的語法:

GMTOffsetTimeZone: 
     GMT Sign Hours : Minutes 
Sign: one of 
     + - 
Hours: 
     Digit 
     Digit Digit 
Minutes: 
     Digit Digit 
Digit: one of 
     0 1 2 3 4 5 6 7 8 9 

此代碼轉換的格式轉換成一個標準,構建一個Java日期對象。

public static Date convertStringWithTimezoneToDate(String dateString) { 
    if (dateString == null) { 
     return null; 
    } 
    dateString += ":00"; 
    System.out.println(dateString); 
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
    Date convertedDate = null; 
    try { 
     convertedDate = dateFormat.parse(dateString); 
    } catch (ParseException e) { 
     e.printStackTrace(); 
    } 
    return convertedDate; 
} 

P.S .:在模式字符串中只需要一個z