Write a Java program to compute the difference between two datetime


  • We import the necessary class java.time.* , which contains classes for working with dates and times.
  • We create a LocalDateTime object dt representing a specific date and time, in this case, September 16, 2022 at midnight.
  • We create a LocalDateTime object dtn representing the current date and time, using the now() method of the LocalDateTime class.
  • We calculate the difference between the two dates using the Duration.between() method of the java.time package, which returns a Duration object representing the duration between two instants.
  • We use the getNano() method of the Duration class to get the number of nanoseconds between the two instants.
  • We use the getSeconds() method of the Duration class to get the number of seconds between the two instants.
  • We use the toMillis() method of the Duration class to get the number of milliseconds between the two instants.
  • We use the toMinutes() method of the Duration class to get the number of minutes between the two instants.
  • We use the toHours() method of the Duration class to get the number of hours between the two instants.
  • Finally, we print the values of the time differences in hours, minutes, milliseconds, seconds, and nanoseconds.

Source Code

import java.time.*;
class Difference_TwoDates
{  
	public static void main(String[] args)
	{
		LocalDateTime dt = LocalDateTime.of(2022, 9, 16, 0, 0);
		LocalDateTime dtn = LocalDateTime.now();
		int nano = java.time.Duration.between(dt, dtn).getNano();
		long sec = java.time.Duration.between(dt, dtn).getSeconds();
		long mili = java.time.Duration.between(dt, dtn).toMillis();
		long min = java.time.Duration.between(dt, dtn).toMinutes();
		long hour = java.time.Duration.between(dt, dtn).toHours();
		System.out.println("Hours : "+hour);
		System.out.println("Minutes : "+min);
		System.out.println("Milliseconds : "+mili);
		System.out.println("Seconds : "+sec);
		System.out.println("Nanoseconds : "+nano);
	}
}

Output

Hours : 1213
Minutes : 72789
Milliseconds : 4367388683
Seconds : 4367388
Nanoseconds : 683228800

Example Programs