There are two excellent answers already. On the occasion of a new duplicate I am diving a little deeper in two directions:
- What to do on java 7?
- How to write a testable version?
For Java 7
If you are still using Java 7, you may still choose which of the other answers you want to use. Micha mentions that java.time was introduced in Java 8. But java.time has also been backported to Java 6 and 7 in the ThreeTen Backport. Getting the backport may seem overkill for getting a Unix timestamp, but if you are doing any more date and time work in your program, I still think that you should consider it. There’s a link at the bottom.
Also dividing by 1000 in your own code may seem a very small thing to do. Still I have made it a habit to leave as much date and time work as possible to the standard library, preferably java.time. There are so many other situations where a conversion seems easy but is easy to get wrong. So I don’t want to do them in my code. So my pure Java 7 solution (without an external library/backport) would probably look like this:
long unixTime = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
System.out.println(unixTime);
1636883947
Now I am also telling the reader why i am dividing by 1000. While the code is a little bit longer, it is also more self-explanatory.
More testable
java.time also offers a testable solution for both Java 7 and 8 and later. We may inject a Clock
, a source of the current time.
Clock clock = Clock.systemUTC();
long unixTime = Instant.now(clock).getEpochSecond();
System.out.println(unixTime);
Output just now:
1636882578
(I ran this on Java 1.7.0_67 using ThreeTen Backport 1.3.6.)
In a test where you need to control which time is used for a reproducible result, for example get a clock with a fixed time:
Clock clock = Clock.fixed(Instant.ofEpochSecond(1_635_936_963), ZoneOffset.UTC);
Now the output from the code is the time we had specified:
1635936963
If all you want the Clock
for is Instant
s, since Java 17 no longer use Clock
. Use InstantSource
.
InstantSource instantSource
= InstantSource.fixed(Instant.ofEpochSecond(1_654_321_098));
long unixTime = instantSource.instant().getEpochSecond();
1654321098
Links