2017-02-10 37 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