Monday, July 18, 2022

Difference between Period and Duration class in Java 8? [Example]

What is the difference between Period and Duration class in Java is one of the popular Java 8 interview questions and has been asked too many of my readers recently. If you were also wondering the difference between Period vs Duration and when to use Period over Duration and vice-versa then you have come to the right place. Java 8 has two classes to represent differences in time like Duration and Period. The main difference between Period and Duration is that they represent the difference in different units, A Duration is used to calculate time difference using time-based values (seconds, millisecond, or hours) but Period is used to measure the amount of time in date-based values like days, months and year.

In order to use Java 8 Date and time API correctly, it's important to understand the difference between these two class, so that you can choose the one which best suits your need. 

You should use Duration to measure the difference in time like the difference between two Instant (milliseconds from epoch), but use Period to calculate the difference between dates. Another key difference between Duration and Period is that Duration doesn't take care of date based events into account like when daylight saving time changes occur or an extra day in a leap year. 


For example, you can call birthDay.plus(Period.ofYears(1)) to get your next birthday, but calling birthday.plus(Duration.ofDays(365)) will not produce a correct result in a leap year, because it has 366 days. 

When you use date-based values like Month or Year, Java will automatically calculate a correct number of days, but with Duration, you need to provide exact days. Let's see a couple of examples of Duration and Period in Java to understand them in more detail.

By the way, if you are new to the Java programming world and want to learn Java in a more structured way then I also recommend you to check out the Complete Java Masterclass course on Udemy. this 80-hour long curse is the best course to learn Java online. 




Difference between Period and Duration class in Java 8

As I said before the main difference between Period and Duration in Java is that the former is used to calculate day based differences like number or days, months, and year between two dates while the latter is used to calculate time-based differences like the number of seconds, minutes, and hour between two Instant. Now, let's see some examples to understand both Period and Duration better. 

1. Java 8 Duration Example

Here is an example of how to use the Duration class in Java 8 to find the difference between two Instant objects in Java. If you look at this example, then you will see that we are just capturing the current time and time after 2 seconds and the difference between those two instants is a Duration object which can be converted into milliseconds. 
Instant start = Instant.now();
TimeUnit.SECONDS.sleep(2);
Instant end = Instant.now();
        
Duration duration = Duration.between(start, end);
long elapsedInMillis = duration.toMillis();
System.out.println("Duration between start and end in millisecond : " 
                + elapsedInMillis);

Output
Duration between start and end in millisecond : 2000


2. Java 8 Period Example

Similar to the previous example, here are have two LocalDate objects instead of two Instant objects. One object represents the current Date while the other objects represent some other date and the difference between them is calculated using the Period.between() method which returns a Period object. Once you have this Period object, you can find the days, months, and years between two dates in Java. 
LocalDate today = LocalDate.now();
LocalDate someDate = LocalDate.of(2015,Month.JULY, 22);
        
Period difference = Period.between(someDate, today);
int days = difference.getDays();
System.out.println("Difference between two dates : " + days);

Output
Difference between two dates : 9




Difference between Duration and Period in JDK 8 - Example

Here is our sample Java program to calculate the difference between Duration and Period in Java 8. In this program, I have shown you how to use both Duration and Period as well as to calculate the difference between two Instance and two LocalDate objects in Java. 
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;



/**
 * Java Program to demonstrate difference between Duration and Period 
 * class in Java 8.
 * 
 * @author WINDOWS 8
 */
public class Java8Demo {
    
    public static void main(String args[]) throws InterruptedException {
      
        // How to use Duration class
        Instant start = Instant.now();
        TimeUnit.SECONDS.sleep(2);
        Instant end = Instant.now();
        
        Duration duration = Duration.between(start, end);
        long elapsedInMillis = duration.toMillis();
        System.out.println("duration between start and end in millisecond : " 
                + elapsedInMillis);
       
        
        // Use Period to find difference between dates
        LocalDate today = LocalDate.now();
        LocalDate someDate = LocalDate.of(2015,Month.JULY, 22);
        
        Period difference = Period.between(someDate, today);
        int days = difference.getDays();
        System.out.println("Difference between two dates : " + days);
        
        
        // difference betwen Duration and Period
        LocalDate aDate = LocalDate.of(2011, Month.MARCH, 1);
        
        // now let's add duration and Period of 1 year into this
        // remember, 2012 was a leap year
        LocalDate after365Days = aDate.plus(365, ChronoUnit.DAYS);
        LocalDate afterAnYear = aDate.plus(Period.ofYears(1));
        
        System.out.println("one date : " + aDate);
        System.out.println("date after 365 days : " + after365Days);
        System.out.println("date after 1 year : " + afterAnYear);
        
    }
    
}

Output :
duration between start and end in millisecond : 2000
Difference between two dates : 9
one date : 2011-03-01
date after 365 days : 2012-02-29
date after 1 year : 2012-03-01


Important Points

1. Duration can be negative if endTime occurs before the start time.

2. Duration provides a method to get duration as millisecond, second, and hours but doesn't have a method to get as days, months, or year. While Period provides methods like getDays(), getMonths() and getYears() to extract those details from a period object.

3. Use duration to calculate the time difference and use Period to calculate date difference in Java.

Also, here is a nice table to highlight the difference between Period and Duration in Java and when to use Period and Duration to find the difference between two Date or Instant in Java.  If you want to learn more, you can further check out these best Java Programming Courses to learn more about Java's Date and Time API. 

Difference between Period and Duration class in Java 8?



That's all about the difference between Duration and Period in Java 8. Use Duration to measure time difference in time-based values like hours, minutes, and seconds, while use Period to calculate elapsed time between two dates like year, months, and days. 

Always use Period while calculating the difference between two dates in days, months, and year, but you can use Duration to find time difference in hours, minutes, and seconds. Use Period while adding yeas into Date to handle leap year.



Other Java date and time tutorials you may like to explore
  • How to convert java. util.Date to java.sql.Timestamp in JDBC? (tutorial)
  • How to parse String to Date using the JodaTime library? (example)
  • How to get the current date and time in Java 6? (tutorial)
  • How to compare two dates in Java? (tutorial)
  • How to convert Date to LocalDateTime in Java 8? (tutorial)
  • How to convert java.util.Date to java.sql.Date in JDBC? (tutorial)
  • 20 Essential Examples of Date and Time API of Java 8? (tutorial)
  • How to get the current Timestamp value in Java? (tutorial)
  • How to convert String to LocalDateTime in Java 8? (example)
  • How to parse String to LocalDateTime in Java 8? (tutorial)
  • Difference between java.sql.Time, java.sql.Timestamp, and java.sql.Date in JDBC? (answer)

Thanks for reading this article so far. If you find the difference between Period and Duration in Java useful then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note. 

P. S. - If you are new to Java world and looking for free training courses to learn Java from scratch then you can also check out this Java Tutorial for Complete Beginners(FREE) course on Udemy. It's completely free and more than 1.2 million people have joined this course to learn Java online. 

2 comments :

Justin W said...

Birthday example is kind of silly because `Period.ofDays(365) would cause the same leap-year "problem".

javin paul said...

Good point

Post a Comment