Date and Time

How to find Days Hours Minutes between two dates in java

Table of Contents

Program

import java.time.LocalDateTime; 
import java.time.Month;
import java.time.temporal.ChronoUnit;

public class NumberOf 
{
	public static void main(String[] args) 
	{
		LocalDateTime beforeDT = LocalDateTime.of(2021,Month.APRIL,1,12,12,12);
		LocalDateTime afterDT = LocalDateTime.of(2021,Month.APRIL,4,12,12,12);
		
		long nfd = ChronoUnit.DAYS.between(beforeDT,afterDT);
		long nfh = ChronoUnit.HOURS.between(beforeDT,afterDT);
		long nfm = ChronoUnit.MINUTES.between(beforeDT,afterDT);
		long nfs = ChronoUnit.SECONDS.between(beforeDT,afterDT);
		
		System.out.println("Number of Days Between two dates    : " + nfd);
		System.out.println("Number of Hours Between two dates   : " + nfh);
		System.out.println("Number of Minutes Between two dates : " + nfm);
		System.out.println("Number of Seconds Between two dates : " + nfs);
	}

}

Output

Number of Days Between two dates    : 3
Number of Hours Between two dates   : 72
Number of Minutes Between two dates : 4320
Number of Seconds Between two dates : 259200

Description

public static final ChronoUnit DAYS

Unit that represents the concept of a day. For the ISO calendar system, it is the standard day from midnight to
midnight. The estimated duration of a day is 24 Hours.
When used with other calendar systems it must correspond to the day defined by the rising and setting of the Sun
on Earth. It is not required that days begin at midnight – when converting between calendar systems, the date should
be equivalent at midday.

public static final ChronoUnit HOURS

Unit that represents the concept of an hour. For the ISO calendar system, it is equal to 60 minutes.

public static final ChronoUnit MINUTES

Unit that represents the concept of a minute. For the ISO calendar system, it is equal to 60 seconds.

public static final ChronoUnit SECONDS

Unit that represents the concept of a second. For the ISO calendar system, it is equal to the second in the SI system of units,
except around a leap-second.