Last Updated:

Finding the difference between two dates in Java

Today we will learn how to find the difference between 2 dates. This article is a continuation of the Java section for beginners. In this article, we will learn how to determine the difference between two dates in Java.

To do this, let's recall how the date is converted from milliseconds to seconds/minutes/hours/days:

  • 1000 milliseconds = 1 second
  • 60,000 milliseconds = 60 seconds = 1 minute
  • 3,600 seconds = 60 minutes = 1 hour
  • 24 hours = 1,440 minutes = 1 day

Now let's just transfer the transformations to the Java example.

Finding the difference between two dates in Java

How do I find the difference between dates in Java?

In the listing below, we create 2 objects in a specific format and get the values of each date in milliseconds using the method and then carry out the transformations presented above:DategetTime()

Now let's run the program and look at the console:

Notice that in the listing, we explicitly subtract the smaller date from the larger date. On the contrary, if we subtract the larger date from the smaller one, then as a result we get the same result, but with a minus sign.