2015-04-02 118 views
0

我有以下字符串「2015-04-02 11:52:00 + 02」,我需要在Java中將它解析爲時間戳。 我試過各種格式,包括在java中的時間戳字符串到時間戳

SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z"); 

,但似乎沒有任何工作 - 我不斷收到一個ParseException

誰能幫助?

我需要這樣的東西:

SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z"); 


Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00+02").getTime()); 
+0

張貼您的StackTrace! – 2015-04-02 14:18:05

+0

線程「main」中的異常java.text.ParseException:Unparseable date:「2015-04-02 11:52:00 + 02」 \t at java.text.DateFormat.parse(Unknown Source) \t at com .. ..... Main.main(Main.java:45) – Alexandr 2015-04-02 14:20:12

+0

不知道你是否可以使用Java 8,但[這篇文章](http://stackoverflow.com/questions/22463062/how-to-parse-format -dates-with-localdatetime-java-8)可以幫助你。 – Pete 2015-04-02 14:38:49

回答

1

嘗試這個

String str="2009-12-31 23:59:59 +0100"; 
           /\ 
           || 
         Provide Space while providing timeZone 

SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); 
System.out.println(mdyFormat.parse(str)); 

輸出

Fri Jan 01 04:29:59 IST 2010 
0

嘗試按以下格式"yyyy-MM-dd HH:mm:ssX"

Z立場時區:+0800

X立場時區的格式如下:+08

例子here

+0

不行,沒有工作。 – Alexandr 2015-04-02 14:24:38

+0

以正確的格式編輯 – jhamon 2015-04-02 14:31:03

0

的java.sql.Timestamp對象不具有時區 - 他們在時刻,像java.util.Date

那麼試試這個:

SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00").getTime()); 
0

ISO 8601

替換空間與T中間,你有一個有效的標準(ISO 8601)的字符串,可以直接通過任一Joda-Time庫或內置到Java 8.0中的新java.time package解析格式(靈感喬達時間)。在數百個示例中搜索StackOverflow。

如果使用java.time,請閱讀我對有關解析小時偏移值時的錯誤的問題的評論。

Joda-Time中的示例2.7。

String inputRaw = "2015-04-02 11:52:00+02"; 
String input = inputRaw.replace(" ", "T"); 
DateTimeZone zone = DateTimeZone.forID("America/Montreal"); // Specify desired time zone adjustment. 
DateTime dateTime = new DateTime(input, zone);