2016-05-03 84 views
1

我想解析Java中的時區字符串的時間戳。我的字符串是:轉換時間戳字符串時獲取無法解析的日期異常

"2013-01-01 15:30:00.2 +05:00" 
"2003-01-01 02:59:04.123 -8:00" 

這是我的代碼來分析它:

java.text.ParseException: Unparseable date: "2013-01-01 15:30:00.2 +05:00" 

我也:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); 
simpleDateFormat.parse("2013-01-01 15:30:00.2 +05:00"); 

不過,我當我運行的代碼收到此錯誤信息試用下面的代碼解析它:

DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis(); 
DateTime dateTime = dateTimeFormatter.parseDateTime("2003-01-01 02:59:04.123 -8:00"); 
Timestamp timeStamp = new Timestamp(dateTime.getMillis()); 

這讓我異常:

Invalid format: "2003-01-01 02:59:04.123 -8:00" is malformed at " 02:59:04.123 -8:00" 

我也試着插入日期後的字符串中的「T」,但它也給了無效格式異常:

Invalid format: "2003-01-01T02:59:04.123 -8:00" is malformed at " .123 -8:00" 

這必須是非常簡單的 - 這不是我不知道我要去哪裏錯了。

感謝您的幫助!

+0

這可能幫助。 http://stackoverflow.com/questions/4542679/java-time-zone-when-parsing-dateformat –

+2

請注意「ISODateTimeFormat.dateTimeNoMillis」的「no millis」部分 - 然後查看您嘗試解析的值。 –

+1

我假設'DateTimeFormatter'代碼是Joda時間,而不是Java 8?如果你在你的帖子中指出這一點會很有用。 –

回答

0

你只是犯了一個錯誤中的SimpleDateFormat(YYYY-MM-DD HH:MM:SS.SSS ž), 其中 'Z' 接受時區與一般時區 presentation.General時區接受:

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 

但你提到的+5:00這應該是GMT + 5:00。

還有'Z''X' 中的SimpleDateFormat分別接受RFC 822 time zoneISO 8601 time zone來表示的時區。

0

試試下面的代碼:只要把GMT + 5:30,而不是+5:30

import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public class DateDemo { 

    // main method 
    public static void main(String[] args) { 

     try { 
      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS z"); 
      Date d = simpleDateFormat.parse("2013-01-01 15:30:00.2 GMT+05:00"); 
      System.out.println(d); 
     } catch (ParseException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

} 
相關問題