Java UnsupportedTemporalTypeException: Unsupported field: InstantSeconds

w‮‬ww.lautturi.com
Java UnsupportedTemporalTypeException: Unsupported field: InstantSeconds

Error

String timestamp = "2018-10-22 17:20:13";
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		Instant result = Instant.from(formatter.parse(timestamp));
Exception in thread "main" java.time.DateTimeException: Unable to obtain Instant from TemporalAccessor: {},ISO resolved to 2018-10-22T17:20:13 of type java.time.format.Parsed
	at java.base/java.time.Instant.from(Instant.java:378)
	at hello.Lautturi.main(Lautturi.java:79)
Caused by: java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: InstantSeconds
	at java.base/java.time.format.Parsed.getLong(Parsed.java:203)
	at java.base/java.time.Instant.from(Instant.java:373)

Solution

add the timezone to the formatter object

/**
 * @author lautturi.com 
 * Java example: java instant from timestamp string
 */


import java.time.Instant;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

import java.util.*;

public class Lautturi {

	public static void main(String[] args) {

		String timestamp = "2018-10-22 17:20:13";
		final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
				.withZone(ZoneId.systemDefault());
		Instant result = Instant.from(formatter.parse(timestamp));

		System.out.println("Instant: " + result);

	}
}

output:

Instant: 2018-10-22T14:20:13Z
Created Time:2017-09-25 11:24:29  Author:lautturi