w3resource logo


Java Programming Exercies

Java DateTime, Calendar Exercises: Compute the difference between two dates (Hours, minutes, milli, seconds and nano)

Secondary Nav

Java DateTime, Calendar : Exercise-31 with Solution

Write a Java program to compute the difference between two dates (Hours, minutes, milli, seconds and nano).

Java Code:

import java.time.*;
import java.util.*;

public class Exercise31 {  
   public static void main(String[] args)
    {
     LocalDateTime dateTime = LocalDateTime.of(2016, 9, 16, 0, 0);
     LocalDateTime dateTime2 = LocalDateTime.now();
     int diffInNano = java.time.Duration.between(dateTime, dateTime2).getNano();
     long diffInSeconds = java.time.Duration.between(dateTime, dateTime2).getSeconds();
     long diffInMilli = java.time.Duration.between(dateTime, dateTime2).toMillis();
     long diffInMinutes = java.time.Duration.between(dateTime, dateTime2).toMinutes();
     long diffInHours = java.time.Duration.between(dateTime, dateTime2).toHours();
     System.out.printf("\nDifference is %d Hours, %d Minutes, %d Milli, %d Seconds and %d Nano\n\n", 
                   diffInHours, diffInMinutes, diffInMilli, diffInSeconds, diffInNano );

  }
}

Sample Output :

Difference is 85 Hours, 5156 Minutes, 309404591 Milli, 309404 Seconds and 591000000 Nano 

Java Practice online:

import java.time.*;
import java.util.*;

public class Exercise31 {  
   public static void main(String[] args)
    {
     LocalDateTime dateTime = LocalDateTime.of(2016, 9, 16, 0, 0);
     LocalDateTime dateTime2 = LocalDateTime.now();
     int diffInNano = java.time.Duration.between(dateTime, dateTime2).getNano();
     long diffInSeconds = java.time.Duration.between(dateTime, dateTime2).getSeconds();
     long diffInMilli = java.time.Duration.between(dateTime, dateTime2).toMillis();
     long diffInMinutes = java.time.Duration.between(dateTime, dateTime2).toMinutes();
     long diffInHours = java.time.Duration.between(dateTime, dateTime2).toHours();
     System.out.printf("\nDifference is %d Hours, %d Minutes, %d Milli, %d Seconds and %d Nano\n\n", 
                   diffInHours, diffInMinutes, diffInMilli, diffInSeconds, diffInNano );
  }
}



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program