Explain Codes LogoExplain Codes Logo

Getting "unixtime" in Java

java
unixtime
java-8
datetime
Nikita BarsukovbyNikita Barsukov·Aug 28, 2024
TLDR

The quickest way to get the current Unix timestamp in seconds in Java:

long unixTime = System.currentTimeMillis() / 1000L; // Divide by 1000 to banish those pesky milliseconds

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):

long unixTime = Instant.now().getEpochSecond(); // Isn't it better when Java does the math for you?

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:

Clock clockForTest = Clock.fixed(Instant.now(), ZoneOffset.UTC); long unixTime = Instant.now(clockForTest).getEpochSecond(); // It's test o'clock!

From Java 17 onwards, there's a better way of testing your skills with InstantSource:

InstantSource testingSource = InstantSource.fixed(Instant.now()); // It's like having a time machine! long unixTime = testingSource.instant().getEpochSecond();

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:

long unixTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); // Have to keep those hands clean for coding

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.