Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse String timestamp to Instant throws Unsupported field: InstantSeconds

I am trying 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 code looks basically like this

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);

I am using Java 8 Update 72.

like image 326
keiki Avatar asked Feb 24 '16 18:02

keiki


2 Answers

A simpler method is to add the default timezone to the formatter object when declaring it

final DateTimeFormatter formatter = DateTimeFormatter
                                    .ofPattern("yyyy-MM-dd HH:mm:ss")
                                    .withZone(ZoneId.systemDefault());
Instant result = Instant.from(formatter.parse(timestamp));
like image 186
jdex Avatar answered Oct 18 '22 15:10

jdex


Here is how to get an Instant with a default time zone. Your String can not be parsed straight 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);
like image 40
Michael Gantman Avatar answered Oct 18 '22 14:10

Michael Gantman