Explain Codes LogoExplain Codes Logo

Calculating the difference between two Java date instances

java
prompt-engineering
java-8
time-unit-conversions
Nikita BarsukovbyNikita Barsukov·Jan 30, 2025
TLDR

Need to calculate the time difference between two Date objects in Java? This is your barebone, quick and dirty solution (do laundry afterwards):

Date date1 = // initial date Date date2 = // end date // Here comes the number crunching long diffMillis = date2.getTime() - date1.getTime(); // The club can't even handle me right now long seconds = TimeUnit.MILLISECONDS.toSeconds(diffMillis); long minutes = TimeUnit.MILLISECONDS.toMinutes(diffMillis); long hours = TimeUnit.MILLISECONDS.toHours(diffMillis); long days = TimeUnit.MILLISECONDS.toDays(diffMillis);

These calculations will display the difference in seconds, minutes, hours, or days. Beware! The result may be negative if date2 is earlier than date1.

Java 8+: Welcome to the future

When java.time came along with Java 8, it brought many gifts, like Duration.between(), that makes time calculation all the more precise:

Instant start = date1.toInstant(); Instant end = date2.toInstant(); // Gonna make you an offer you can't refuse Duration duration = Duration.between(start, end);

Baby light my fire

Whatever you do with Date objects, beware of pitfalls like the Daylight Saving Time. But don’t be alarmed, ZonedDateTime can save your day (and your night):

ZonedDateTime zdt1 = date1.toInstant().atZone(ZoneId.systemDefault()); ZonedDateTime zdt2 = date2.toInstant().atZone(ZoneId.systemDefault()); // Don't worry, we've got you covered with ZonedDateTime long hours = ChronoUnit.HOURS.between(zdt1, zdt2);

In the world of JodaTime and ThreeTen-Extra

Joda may seem a bit outdated, but it's still got moves. However, if you're living the java.time life, you might enjoy the bonus features from ThreeTen-Extra:

Interval interval = new Interval(date1.getTime(), date2.getTime()); // I'm free, anytime

Attention to detail: Reliable results for the cool kids

Speaking the ISO 8601 language

You gotta speak the language of the lands, and in time calculations, that language is ISO 8601 time durations language:

String isoDuration = duration.toString(); // outputs P3D for 3 days, for instance // See? Now you're fluent!

Testing: The code whisperer

Remember, testing is not just good practice. When it comes to time and dates it can really save your behind (cough Daylight Savings cough)*. So don't forget to run those unit tests on edge cases!

Playing with granularity with TimeUnit conversions

Variety is the spice of life and code. Reverse the TimeUnit order for getting comfortable with granularity:

long days = TimeUnit.MILLISECONDS.toDays(diffMillis); long hours = TimeUnit.MILLISECONDS.toHours(diffMillis - TimeUnit.DAYS.toMillis(days)); long minutes = TimeUnit.MILLISECONDS.toMinutes(diffMillis - TimeUnit.DAYS.toMillis(days) - TimeUnit.HOURS.toMillis(hours)); // Hey TimeUnit, back at it again with the conversions!

Flight booking app example

In real life, time calculation can look something like determining layover times in a flight booking app:

Flight f1 = // incoming flight with landing timestamp Flight f2 = // outgoing flight with departure timestamp // In case you never knew how long layovers feel... long layoverMinutes = TimeUnit.MILLISECONDS.toMinutes(f2.getDepartureTime().getTime() - f1.getLandingTime().getTime());

User-friendly view

Your users will appreciate durations represented in a human readable form:

String humanReadable = String.format("%d hours, %d minutes", TimeUnit.MILLISECONDS.toHours(diffMillis), TimeUnit.MILLISECONDS.toMinutes(diffMillis) % 60); // Because now it's not only numbers, it's poetry!