2017-04-20 36 views
-1

當我運行下面的代碼將時間字符串轉換爲Java日期時,它失敗。如何在Java中使用偏移時間簡單日期格式

String s = "04/17/2017 06:46:53 -600"; 
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z"); 
Date value = format.parse(s); 

Exception in thread "main" java.text.ParseException: Unparseable date: "04/17/2017 06:46:53 -600" 
    at java.text.DateFormat.parse(Unknown Source) 

什麼是用於將日期字符串轉換爲java日期的正確格式字符串?

+6

可能需要'-0600'不'-600' – AxelH

+0

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html#rfc822timezone – 1615903

+0

請參閱http:// stackoverflow.com/questions/9541043/java-convert-string-to-date-in-with-time-zone-variable?rq=1 – 2017-04-20 11:48:15

回答

2

添加-0600代替-600 read link

import java.text.*; 
import java.util.*; 
class TestFormatDate { 


public static void main(String arg[]) throws Exception{ 

String s = "04/17/2017 06:46:53 -0600"; 
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss Z"); 
Date value = format.parse(s); 
System.out.println("value "+value); 
} 
} 
2

作爲SimpleDateFormat time zone documentation解釋:

RFC 822時區:對於格式化,在RFC 822的4位時區格式被用於:

RFC822TimeZone: 
     Sign TwoDigitHours Minutes 
TwoDigitHours: 
     Digit Digit 

ISO 8601時區:模式字母的數量指定格式化和解析的格式,如下所示:

ISO8601TimeZone: 
     OneLetterISO8601TimeZone 
     TwoLetterISO8601TimeZone 
     ThreeLetterISO8601TimeZone 
    OneLetterISO8601TimeZone: 
     Sign TwoDigitHours 
     Z 
    TwoLetterISO8601TimeZone: 
     Sign TwoDigitHours Minutes 
     Z 
    ThreeLetterISO8601TimeZone: 
     Sign TwoDigitHours : Minutes 
     Z 

時間總是看到兩個數字,所以你需要通過-0600作爲一個時區或-06

只有這樣,你可以有一個數的小時數是:

一般時區:如果時區具有名稱,則將其解釋爲文本。對於表示GMT偏移值的時區時,使用的語法如下:

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 
0

嘗試,

String s = "04/17/2017 06:46:53 -0600"; 

請仔細閱讀this檢查如何使用「Z」。

相關問題