Along with lambda expression, virtual methods, streams and many other nice features, Java 8 has also updated a new Date and Time API which is maintained under the JSR-310.
In my previous articles I have explained about the LocalDate and LocalTime . These new API has added very useful Period and Duration classes to ease the programmers job for time calculations. This example demonstrates how to use java.time.Period and java.time.Duration and what is the main difference between these two classes.
If you have any clarifications, please write it in the comments section or post it in our facebook page. You can read more articles on Java 8 here.
Difference Between Period and Duration
With Java 8, we have two new classes Period and Duration for measuring the date/time in a scale. Period is a date based amount of time.This class denotes the amount of time in Years, Months and Days. Where as, Duration is a time based amount of time. This class denotes the amount of time in hours, minutes and seconds. Duration practically stores the time similar to java.time.Instant class which stores in the nanoseconds.
Coming to the point, actual different between Period and Duration lies in how they calculate the time difference. Duration is most suitable when we measure machine based timings where as Period is most suitable when we want to know the human readable time representation. For example, when you want to find age using the current date and birth date, Period makes more sense. If you look at the below example, it is easy to understand the difference.
Example
package javabeat.net; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.Month; import java.time.Period; /** * Difference Between Period and Duration * @author www.javabeat.net * */ public class PeriodDurationDifferenceExample { public static void main(String[] args) { //Calculate Birth Day using Period class LocalDate localDate = LocalDate.now(); LocalDate bDay = LocalDate.of(1980, Month.OCTOBER, 12); Period age = Period.between(localDate, bDay); System.out.println("Current Age : "+age); //Calculate time different using Duration class Instant instant1 = Instant.now(); Instant instant2 = instant1.plusSeconds(3600); Duration duration = Duration.between(instant1, instant2); System.out.println("Time Duration : "+duration); } }
Output for the above program will be:
Current Age : P-34Y-6M Time Duration : PT1H
One important point is that, when you try to use the LocalDate for calculating the Duration, you would encounter the following exception. You have to use Instant class for Duration calculation.
Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds at java.time.LocalDate.until(LocalDate.java:1608) at java.time.Duration.between(Duration.java:475) at javabeat.net.PeriodDurationDifferenceExample.main(PeriodDurationDifferenceExample.java:16)