uksz
uksz

Reputation: 18719

DateTimeFormatter exception

I am having issues with the DateTimeFormatter in Java.

I have the following code:

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDateTime startDate = LocalDateTime.now();
LocalDateTime endDate = LocalDateTime.parse(ceremonyDetails.getDate(), format);
System.out.println(ChronoUnit.DAYS.between(startDate, endDate)); format);

Which should print days between now and date from string, of format 'dd/MM/yyyy', such as '29/09/2016'.

However, I am getting this error:

java.time.format.DateTimeParseException: Text '29/09/2016' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {},ISO resolved to 2016-09-29 of type java.time.format.Parsed] with root cause java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {},ISO resolved to 2016-09-29 of type java.time.format.Parsed

What am I missing?

Upvotes: 1

Views: 3710

Answers (1)

Scary Wombat
Scary Wombat

Reputation: 44854

You should use LocalDate rather than LocalDateTime. One is for a date-only value, the other for a date with time-of-day value.

LocalDate.parse( "29/09/2016" , DateTimeFormatter.ofPattern("dd/MM/yyyy") )

See examples on the DateTimeFormatter class documentation page.

Upvotes: 3

Related Questions