Java 8 date/time:即时,无法在索引 19 处解析

Java 8 date/time: instant, could not be parsed at index 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);

它给了我以下异常:

Exception in thread "main" 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(DateTimeFormatter.java:1851) at java.time.Instant.parse(Instant.java:395) at core.domain.converters.TestDateTime.main(TestDateTime.java:10)

当我将最后一个冒号更改为句号时:

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

...然后执行正常:

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

所以,问题是 - 如何使用 InstantDateTimeFormatter 解析日期?

使用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[Europe/Kiev]

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,可以直接解析String,不需要转换。

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

其中"problem"是毫秒前的冒号,即non-standard(标准为小数点)

要使其正常工作,您必须为您的自定义格式构建自定义 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]

如果你的日期时间文字有一个点而不是最后一个冒号,事情会简单得多。