Calculating the difference between two Java date instances
Need to calculate the time difference between two Date
objects in Java? This is your barebone, quick and dirty solution (do laundry afterwards):
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:
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):
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:
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:
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:
Flight booking app example
In real life, time calculation can look something like determining layover times in a flight booking app:
User-friendly view
Your users will appreciate durations represented in a human readable form:
Was this article helpful?