Getting "unixtime" in Java
The quickest way to get the current Unix timestamp in seconds in Java:
This immediately computes the Unix time, by succinctly converting the system's current time into seconds.
Handling Unix time in Java: Doing it better
When dealing with time in Java, you're ultimately working with Unix time, a.k.a. Epoch time. Here you'll discover different ways to tackle Unix time in Java, from old faithful to new hotness.
Embracing java.time
in Java 8+
Consistency checks out? Time to move on to Java's modern time handling with JSR 310 (Java 8 and onwards):
Believe it or not, this method hands you the Unix time in seconds with no fuss.
Testing around time? Try Clock
or InstantSource
If you're writing test cases, Clock
has your back:
From Java 17 onwards, there's a better way of testing your skills with InstantSource
:
Testing time-dependent code just got easier and more robust.
Squeaky clean conversions with TimeUnit
Maybe you're dealing with milliseconds and need to convert to seconds. Instead of doing the division yourself, let's employ TimeUnit
to do the heavy lifting:
Why lowercase 'l' matters
The constant 1000L
uses the lowercase 'l' to improve readability because it's awfully easy to mistake '1' for 'l', and we have enough trouble with semicolons.
Before Java 8
Running Java 6 or 7? You can still use features from java.time
via the ThreeTen Backport project. Because not everyone can live in the future, right?
Android Compatibility
Working on Android or older platforms? You can still use java.time
APIs on older versions with desugaring, a pretty sweet method for maintaining cool code on all platforms.
Referral?
Do refer to the Oracle tutorial on Date Time for expanding your java.time
prowess.
Was this article helpful?