2017-02-10 39 views
2

我有下面這段代碼:的Java 8日期/時間:瞬發,無法在指數解析19

String dateInString = "2016-09-18T12:17:21:000Z"; 
Instant instant = Instant.parse(dateInString); 

ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Europe/Kiev")); 
System.out.println(zonedDateTime); 

它給了我以下異常:在線程

異常「主」 java.time.format.DateTimeParseException: Text'2016-09-18T12:17:21:000Z'could not be parsed at index 19 at java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:1949) at java.time.format.DateTimeFormatter.parse(DateTimeForm atter.java:1851) 在java.time.Instant.parse(Instant.java:395)在 core.domain.converters.TestDateTime.main(TestDateTime.java:10)

當我改變最後一個冒號完全停止:

String dateInString = "2016-09-18T12:17:21.000Z"; 

...然後去執行罰款:

2016-09-18T15:17:21 + 03:00 [歐洲/基輔]

所以,問題是 - 如何解析日期InstantDateTimeFormatter

回答

3

「問題」是毫秒前的冒號,這是不規範(標準是小數點)。

要使其工作,你必須建立一個自定義DateTimeFormatter爲您的自定義格式:

String dateInString = "2016-09-18T12:17:21:000Z"; 
DateTimeFormatter formatter = new DateTimeFormatterBuilder() 
    .append(DateTimeFormatter.ISO_DATE_TIME) 
    .appendLiteral(':') 
    .appendFraction(ChronoField.MILLI_OF_SECOND, 3, 3, false) 
    .appendLiteral('Z') 
    .toFormatter(); 
LocalDateTime instant = LocalDateTime.parse(dateInString, formatter); 
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Europe/Kiev")); 
System.out.println(zonedDateTime); 

輸出這個代碼:

2016-09-18T12:17:21+03:00[Europe/Kiev] 

如果你的日期時間字面有一個點,而不是最後一個冒號的東西會簡單得多。

+0

事實上的標準是逗號*或*句號(週期),與**逗號優選**。參見* ISO 8601:2004 *第三版2004-12-01,「4.2.2.4帶小數的表示法」部分:...小數部分應從整數部分除以ISO 31-0中規定的小數點,即逗號[,]或句號[。]。其中,逗號是首選標誌。... –

+0

@basil可能是ISO,但不在JDK中,[使用小數點](http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatterBuilder.html# appendFraction-java.time.temporal.TemporalField-INT-INT-boolean-) – Bohemian

1

使用SimpleDateFormat

String dateInString = "2016-09-18T12:17:21:000Z"; 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS"); 
Instant instant = sdf.parse(dateInString).toInstant(); 
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of("Europe/Kiev")); 
System.out.println(zonedDateTime); 

2016-09-18T19:17:21 + 03:00 [歐洲/基輔]

-1
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/MM/yyyy"); 

String date = "16/08/2016"; 

//convert String to LocalDate 
LocalDate localDate = LocalDate.parse(date, formatter); 

如果String的格式如下ISO_LOCAL_DATE,您可以直接解析字符串,無需轉換。

package com.mkyong.java8.date; 

import java.time.LocalDate; 

public class TestNewDate1 { 

    public static void main(String[] argv) { 

     String date = "2016-08-16"; 

     //default, ISO_LOCAL_DATE 
     LocalDate localDate = LocalDate.parse(date); 

     System.out.println(localDate); 

    } 

} 

看看這個網站 Site here

+0

什麼時間部分? – Bohemian