2015-04-03 119 views
-4

我真的很感激任何人都可以幫忙。 我在字符串中獲取日期(2014-11-12T00:00:00Z),現在我想轉換爲格式(2014-11-12T00:00:00-04:00)。Java字符串日期轉換問題

How can we do that in java? 

回答

0

你可以嘗試使用JodaTime

String str = "2014-11-12T00:00:00Z"; 
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ"; 
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern); 
DateTime dateTime = dtf.parseDateTime(str); 
System.out.println(dateTime); //2014-11-12T00:00:00-04:00 

編輯:

String s = "2014-11-12T00:00:00Z"; 
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ"; 
Date date = new SimpleDateFormat(pattern, Locale.ENGLISH).parse(s); 
DateTime d = new DateTime(date.getTime()); 
System.out.println(d); 
+0

我得到以下例外,當我在線程「主」 java.lang.IllegalArgumentException異常以上suggestion.Exception使用:無效的格式:「2014-11-12T00:00:00Z」在「Z格式有誤「 \t在org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:673) \t在com.guthyrenker.customizationoffer.transformer.Test.main(Test.java:31) – user3157090 2015-04-03 12:48:45

+0

@ user3157090: - 以上例外是因爲某些時區縮寫不明確,分析程序無法知道哪個時區的含義。 'z'時區名稱是常規(非標準化)和含糊 – 2015-04-03 12:51:20

+0

應該怎麼做才能克服這個錯誤? – user3157090 2015-04-03 12:52:11

0

喬達時間

使用喬達時庫,或類似java.time包內置於Java 8中。

使用proper name指定所需的時區。避免3或4個字母代碼,因爲它們既不標準也不唯一。

ISO 8601

您的字符串格式符合ISO 8601標準。在Joda-Time和java.time中默認使用該標準來解析和生成字符串。

Joda-Time中的示例2.7。

DateTimeZone zone = DateTimeZone.forID("America/Martinique"); 
DateTime dateTime = new DateTime(yourInputString, zone); 
String output = DateTime.toString();