Over a million developers have joined DZone.

Finding the Difference Between Two Dates in Java

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

Let’s say you have two Date objects DateOne and DateTwo. Now you want to find the difference between these two dates and show that in a human readable format; for example “the difference is 2 hours and 30 minutes“. How do you do it in Java?

The obvious answer is, get the milliseconds from these two dates and find the difference. And, then manually convert these milliseconds into hours, minutes, seconds etc.

But, wait a second. There’s an easy way to do this using the TimeUnit class. TimeUnit represents time durations at a given unit of granularity and provides utility methods to convert across units, and to perform timing and delay operations in these units.

Have a look the below code which finds out the difference between two dates and returns them in the form of “h hours and m minutes”.

public String getTimeDiff(Date dateOne, Date dateTwo) {        String diff = "";        long timeDiff = Math.abs(dateOne.getTime() - dateTwo.getTime());        diff = String.format("%d hour(s) %d min(s)", TimeUnit.MILLISECONDS.toHours(timeDiff),                TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));        return diff;}

That simple, isn’t it?

From http://veerasundar.com/blog/2011/04/finding-the-difference-between-two-dates-in-java/

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:
java,date-time

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}