Java 8 Date-Time API – Period & Duration

Period & Duration classes represent difference between 2 instances of temporal objects i.e. objects that represent date, time, zone etc.

  • Period – Difference between two temporal objects in measured years plus months plus days ex: 1 year and 2 months and 3 days.
  • Duration – Different between two temporal objects in seconds but can be interpreted in days, hours, minutes, seconds, millis. ex: 1 day or 24 hours etc.

Period Examples:

Period between LocalDate objects

Period between LocalDateTime objects.

  • Period is representative of difference in years, months & days. It can’t count time units.
  • So Period does not directly provide method to calculate based on LocalDateTime.
  • There is a way to get Period between LocalDateTime i.e. convert LocalDateTime to LocalDate so that there is no time involved & then Period can be calculated between LocalDate.

Period between YearMonth

  • Unlike earlier example where we had extra information of time, in this case we have missing information i.e. days. We only have Year & Month information.
  • So again Period can’t logically be derived from YearMonth & Period class does not provide facility to do so.
  • But again, you can convert it to LocalDate by taking “first day of month” as a filler day.

Period between ZonedDateTime & OffsetDateTime

  • In this case, we have additional information of time & zone which Period can’t use because it is representation in years, months & days.
  • So here as well, we can convert it into LocalDate & calculate Period.

Period Between Instant

  • instant is moment in time stored in milliseconds which is kind of machine time.
  • To calculate period, we have to bring it to human readable date i.e. LocalDate.



Duration Examples

Duration between LocalDateTime

Duration between LocalTime

Duration between ZonedDateTime and OffsetDateTime

Duration between Instant

Duration between LocalDate

  • Duration is calculated in seconds, but LocalDate only has day, month & year. It doesn’t have time information which makes it ineligible for Duration calculation.
  • If you try to calculate duration between LocalDate objects directly you will get exception  java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds
  • If you still want to calculate duration between LocalDate then you can convert it to LocalDateTime by taking filler “time” as start of day.

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *