user2254180
user2254180

Reputation: 856

Unable to obtain ZonedDateTime from TemporalAccessor:

I have a date in the following format, I need to parse it and convert to an epoch time.

2018-11-08 08:17:18.696124

I have the following code.

String dateString = "2018-11-08 08:17:18.696124";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
ZonedDateTime dateTime = ZonedDateTime.parse(dateString, fmt); 

When I run, I get the following error.

Text '2018-11-08 08:17:18.696124' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {},ISO resolved to 2018-11-08T08:17:18.696124 of type java.time.format.Parsed

Any help on what I am doing wrong here?

Upvotes: 1

Views: 4120

Answers (1)

Michael
Michael

Reputation: 44210

A zoned date time, as the name suggests, needs a zone. Your timestamp format does not include one, so the parsing fails.

You should parse into a LocalDateTime and then apply the correct zone. For example:

String dateString = "2018-11-08 08:17:18.696124";
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS");
LocalDateTime dateTime = LocalDateTime.parse(dateString, fmt);
ZonedDateTime london = dateTime.atZone(ZoneId.of("Europe/London"));

Upvotes: 3

Related Questions