2016-05-27 54 views
3

我有一個新的Java日期API的問題,尤其是java.time.DateTimeFormatterDateTimeFormatter有沒有像Joda的DateTimeFormatter#withOffsetParsed()方法?

我正在尋找一種將TimeZone-Offset添加到給定時間的方法。

例如

"2016-05-27 14:22:00 UTC+2" 

應該解釋爲

"27.05.2016 16:22:00" 

(使用模式 「DD.MM.YYYY HH:MM:SS」)

這是我的問題的代碼:

LocalDateTime time = LocalDateTime.now(); 
LOG.debug(time.format(DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss")); 

格式化會生成與給定模式匹配的時間字符串,但不會考慮本地TimeZone的偏移量。

+0

你想要16:22(如:加2個小時的時間在初始字符串)或者你想要12:22(如:UTC時區的本地時間)?如果前者,您可能需要手動解析字符串的結尾,如果前者可以先使用OffsetDateTime。 – assylias

回答

-1

是的,你可以指定一個你想要考慮的偏移量。 你可以用幾種不同的方式做到這一點,但我會分享 一段代碼,可以讓你去。

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Local.US); 

這是如何使用模式和偏移集創建格式化對象的示例。

+0

您在這裏使用的是傳統日期API ... – assylias

+0

@assylias對不起,只是想提供一個簡單的例子。 – codex

1

應用時區,偏移和格式的多種方法之一。它將有助於在Joda和Java 8之間切換。

的Java 8日期/時間API

String input = "2016-05-27 14:22:02 UTC+0200"; 
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss 'UTC'Z"); 
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss"); 
LocalDateTime localDateTime = parser.parse(input, LocalDateTime::from); 
System.out.println(localDateTime); //2016-05-27T14:22:02 
//Apply different offset on the above instant. 
OffsetDateTime offsetDateTime = parser.parse(input, OffsetDateTime::from).withOffsetSameInstant(ZoneOffset.of("+07:00")); 
System.out.println(offsetDateTime); //2016-05-27T19:22:02+07:00 
//Apply different timezone on the above instant. 
ZonedDateTime zonedDateTime = parser.parse(input, ZonedDateTime::from).withZoneSameInstant(ZoneId.of("Asia/Jakarta")); 
System.out.println(zonedDateTime);// 2016-05-27T19:22:02+07:00[Asia/Jakarta] 
//Apply formatting 
System.out.print(formatter.format(zonedDateTime));//27.05.2016 19:22:02 

喬達API

String input = "2016-05-27 14:22:02 UTC+0200"; 
DateTimeFormatter parser = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss 'UTC'Z"); 
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss"); 
LocalDateTime localDateTime = parser.parseLocalDateTime(input); 
System.out.println(localDateTime);//2016-05-27T14:22:02.000 
//Apply the above offset to the date time 
DateTime offsetParsedDateTime = parser.withOffsetParsed().parseDateTime(input); 
//Change to new Offset 
DateTime jakartaDateTimeOffset = offsetParsedDateTime.toDateTime(DateTimeZone.forOffsetHours(7)); 
System.out.println(jakartaDateTimeOffset);//2016-05-27T19:22:02.000+07:00 
//Change to new Zone 
DateTime jakartaDateTimeZone = offsetParsedDateTime.toDateTime(DateTimeZone.forID("Asia/Jakarta")); 
System.out.println(jakartaDateTimeZone);//2016-05-27T19:22:02.000+07:00 
//Apply formatting 
System.out.print(formatter.print(jakartaDateTimeZone));//27.05.2016 19:22:02 
+0

這個想法是解析輸入字符串而不會對偏移進行編碼... – assylias

+0

這有幫助。謝謝 – Tente

相關問題