当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Parsing timestamp to convert to Instant throws Unsupported field: InstantSeconds

问题描述:

I try to convert a String into an Instant. Can you help me out?

I get following exception:

Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds

at java.time.format.Parsed.getLong(Parsed.java:203)

at java.time.Instant.from(Instant.java:373)

My try looks basically like this

@Test

public void canConvertStringToInstant() {

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

String timestamp = "2016-02-16 11:00:02";

TemporalAccessor temporalAccessor = formatter.parse(timestamp);

Instant result = Instant.from(temporalAccessor);

Instant expectedTimestamp = Instant.parse("2016-02-16T10:00:01.00Z");

assertEquals(expectedTimestamp, result);

}

Using Java 8 update 72

网友答案:

Here is how to get an Instant with default time zone. Your String can not be parsed strait to Instant because timezone is missing. So you can always get the default one

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    String timestamp = "2016-02-16 11:00:02";
    TemporalAccessor temporalAccessor = formatter.parse(timestamp);
    LocalDateTime localDateTime = LocalDateTime.from(temporalAccessor);
    ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.systemDefault());
    Instant result = Instant.from(zonedDateTime);
分享给朋友:
您可能感兴趣的文章:
随机阅读: