I am trying to learn the new Date & Time API. My code is working except for the last line:
LocalDate current=LocalDate.now();
System.out.println(current);
LocalDate personaldate=LocalDate.of(2011,Month.AUGUST, 15);
System.out.println(personaldate);
LocalDate afterten=current.plus(Period.ofDays(10));
System.out.println(afterten);
// error occurs here
System.out.println(afterten.plus(Duration.ofDays(3)));
When I try and add a Duration in days, it generates an error. Can anyone help me understand why?
Error:
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds
at java.time.LocalDate.plus(LocalDate.java:1241)
at java.time.LocalDate.plus(LocalDate.java:137)
at java.time.Duration.addTo(Duration.java:1070)
at java.time.LocalDate.plus(LocalDate.java:1143)
at TestClass.main(TestClass.java:15)
Whilst the accepted answer is completely correct, when I arrived at this question, I was looking for a simple solution to my problem.
I found using Period would not allow me to count the number of days between my two LocalDate objects. (Tell me how many years, months and days between the two, yes, but not just then number of days.)
However, to get the result I was after was as simple as adding the LocalDate method "atStartOfDay" to each of my objects.
So my erronious code:
long daysUntilExpiry = Duration.between(LocalDate.now(), training.getExpiryDate()).toDays();
was simply adjusted to:
long daysUntilExpiry = Duration.between(LocalDate.now().atStartOfDay(), training.getExpiryDate().atStartOfDay()).toDays();
Doing this make the objects into LocalDateTime objects which can be used with Duration. Because both object have start of day as the "time" part, there is no difference.
Hope this helps someone else.