$show=/label

Java 8 - Period and Duration Examples

SHARE:

A quick guide to how to get the differences between the two dates. Mainly Period works with dates based and Duration works with time based values.

1. Overview

In this tutorial, you'll learn Period and Duration usages in java 8 with examples.

Both of these classes are used for same purpose to represent the time based value and find the differences between two dates.

The main differences between these two is that Period class works with date based values where as Duration works with time based values.

Java 8 - Period and Duration



2. Period Class and Examples


The core point is that Period class represents the Year, Month and Day values of date.

2.1 Period object can be obtained from Period.between(startDate, endDate) method which takes two date objects.
2.2 Once you get the Period object then you can use getYear(), getMonth() and getDay() methods to get the specific part of the date object.
2.3 isNegative() method returns true if any of period value is negative value and that indicates that endDate > startDate.
2.4 isNegative() method returns false if the startDate > endDate
2.5 Use Period class methods of(), ofDays(), ofMonths(), ofYears(), ofWeeks() methods to get the Period object.
2.6 If you use ofDays() method, then other properties are set to 0. That means year value will become 0.
2.7 ofWeeks() method sets the no of days value internally to 7 * n where n is the no of weeks.
2.8 Period object can be created from a String value using parse() method. but string should be followed a syntax "PnYnMnD". Here, P indicates the Period, Y - years, M - months, D days. For example, "P2Y" means create a Period object with 2 years and others are set to 0.
2.9 Period values can be increased or decreased using plusXXX() and minusXXX() methods where XXX indicates any date unit.

Example:

In the below example, we have covered the all points described.
package com.javaprogramto.java8.dates.period;

import java.time.LocalDate;
import java.time.Period;

public class PeriodExample {

	public static void main(String[] args) {

		// Creating two dates
		LocalDate startDate = LocalDate.of(2020, 11, 01);
		LocalDate endDate = LocalDate.of(2021, 12, 31);
		
		// printing the start and end dates
		System.out.println("Start Date : "+startDate);
		System.out.println("End Date : "+endDate);

		// getting the differences between startDate and endDate
		Period periodDiff = Period.between(startDate, endDate);
		System.out.println("Period values - year : " + periodDiff.getYears() + ", Months : " + periodDiff.getMonths()
				+ ", Days : " + periodDiff.getDays());

		// checking the diff is negative
		boolean isNegative = periodDiff.isNegative();
		
		if(isNegative) {
			System.out.println("endDate is greater than startDate");
		} else {
			System.out.println("startDate is greater than endDate");
		}
		
		// Different ways to get Period objects
		Period period1 = Period.of(2,10, 30);
		Period periodDays = Period.ofDays(2);
		Period periodWeeks = Period.ofWeeks(10);

		System.out.println("period1 years : "+period1.getYears());
		System.out.println("periodDays days : "+periodDays.getDays());
		System.out.println("periodDays months : "+periodDays.getMonths());
		System.out.println("periodWeeks weeks : "+periodWeeks);
		System.out.println("periodWeeks days : "+periodWeeks.getDays());
		
		// Creating Period object from String
		Period periodParse1 = Period.parse("P2Y2M2D");
		System.out.println("Period days : "+periodParse1.getDays());
		
		Period periodParse2 = Period.parse("P3M4D");
		System.out.println("Period months : "+periodParse2.getMonths());
	}
}
 
Output:
Start Date : 2020-11-01
End Date : 2021-12-31
Period values - year : 1, Months : 1, Days : 30
startDate is greater than endDate
period1 years : 2
periodDays days : 2
periodDays months : 0
periodWeeks weeks : P70D
periodWeeks days : 70
Period days : 2
Period months : 3
 

3. Duration Class and Examples


Duration class represents time interval including seconds or milli or nano seconds. This is mainly suitable for time difference accuracy for smaller time ranges.

3.1 Use Duration.between(instant1, instant2) method to get the differences between two time Instants. This is the way to get the Duration object from between() method.
3.2 From the returned object from between() method, you can call getSeconds(), getNanoSeconds() methods to get the exact difference that make more precision.
3.3 And alos, you can pass LocalDateTime, LocalDate and LocalTime objects to the between() method which will return the new Duration object. This is another way to get the Duration object from different type of java 8 date time api classes.
3.4 You can use the isNegetive() method which returns boolean value as similar in Period class. If it returns true means instant2 is greater than instant1.
3.5 We can obtain the Duration object from another set of time units such as ofDays(), ofMinutes(), ofHours(), ofMillis(), ofNanos() methods.
3.6 Duration can be created from string using parse() method. This string should be in form of "PTnDTnHnMn.nS".
3.7 Duration object created from ofDays() or any method and this duration object can be converted into another time units using toHours(), toDays(), toMinutes(), toSeconds(). This time unit conversion is not available in Period class.
3.8 A duration is allowed to increase or decrease the time units using plus(), minus(), plusXXX() and minusXXX() methods.

Example:
package com.javaprogramto.java8.dates.duration;

import java.time.Duration;
import java.time.Instant;
import java.time.LocalTime;

public class DurationExample {

	public static void main(String[] args) {

		// creating Instance Objects
		Instant instant1 = Instant.parse("2020-11-30T20:30:40.00Z");
		Instant instant2 = Instant.parse("2020-11-30T20:31:40.00Z");

		// printing instnat objects
		System.out.println("Instant 1: " + instant1);
		System.out.println("Instant 2: " + instant2);

		// getting the time diff
		Duration duration = Duration.between(instant1, instant2);
		System.out.println("Diff between instance1 & instance2 in seconds : " + duration.getSeconds());

		// Diff b/w two LocalTime objects
		int nanos = Duration.between(LocalTime.now(), LocalTime.now()).getNano();
		System.out.println("Time diff in nanos : " + nanos);

		boolean isNegative = duration.isNegative();
		if (isNegative) {
			System.out.println("instant2 is greater than instant1");
		} else {
			System.out.println("instant1 is greater than instant2");
		}

		// Different ways to get Duration objects
		Duration durationDays = Duration.ofDays(2);
		Duration durationHours = Duration.ofHours(10);

		System.out.println("durationDays seconds : " + durationDays.getSeconds());
		System.out.println("durationDays nanos : " + durationDays.getNano());
		System.out.println("durationHours seconds : " + durationHours);
		System.out.println("durationHours seconds : " + durationHours.getSeconds());

		// Creating Duration object from String
		Duration durationParse1 = Duration.parse("PT2H");
		System.out.println("Duration seconds : " + durationParse1.getSeconds());

		Duration durationParse2 = Duration.parse("PT10S");
		System.out.println("Duration seconds : " + durationParse2.getSeconds());
	}
}
 
Output:
Instant 1: 2020-11-30T20:30:40Z
Instant 2: 2020-11-30T20:31:40Z
Diff between instance1 & instance2 in seconds : 60
Time diff in nanos : 32000
instant1 is greater than instant2
durationDays seconds : 172800
durationDays nanos : 0
durationHours seconds : PT10H
durationHours seconds : 36000
Duration seconds : 7200
Duration seconds : 10
 

4. Conclusion


In this article, you've seen the core differences between period and duration and when to use which one.

All the examples are show on GitHub.


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 - Period and Duration Examples
Java 8 - Period and Duration Examples
A quick guide to how to get the differences between the two dates. Mainly Period works with dates based and Duration works with time based values.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAv-qeCceKe-SViEFRmWE9sc7LC3u9xGLfCWGto05YzwJcLt-opWBldZeqR9WVXQbdckdMkTqzCEmjYmz9ZXpyWCS7log3Rl1VVM49xBKqtMtrYDXgCXS-64FQ10EY34ORao45njpsyTM/w640-h468/Java+8+-+Period+and+Duration.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjAv-qeCceKe-SViEFRmWE9sc7LC3u9xGLfCWGto05YzwJcLt-opWBldZeqR9WVXQbdckdMkTqzCEmjYmz9ZXpyWCS7log3Rl1VVM49xBKqtMtrYDXgCXS-64FQ10EY34ORao45njpsyTM/s72-w640-c-h468/Java+8+-+Period+and+Duration.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/java-period-duration.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/java-period-duration.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content