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.
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));
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With