Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Friday, November 27, 2020

Java 8 - Period and Duration Examples

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.


No comments:

Post a Comment

Please do not add any spam links in the comments section.