Unix Timestamp in Java
Modern Java uses java.time: Instant.now().getEpochSecond() for the current second, and Instant.ofEpochSecond(ts) to rebuild an instant. System.currentTimeMillis() remains for milliseconds.
Get & convert epoch time in Java
import java.time.Instant; Instant t = Instant.ofEpochSecond(1700000000L); // 2023-11-14T22:13:20.000Z long now = Instant.now().getEpochSecond();
Gotcha: Avoid the legacy java.util.Date; java.time.Instant is immutable, unambiguous (UTC), and far less error-prone.
Frequently asked questions
- How do I get the current Unix timestamp in Java?
- Instant.now().getEpochSecond() for seconds, or System.currentTimeMillis() for milliseconds.
- How do I convert a timestamp to a date in Java?
- Instant.ofEpochSecond(ts).atZone(ZoneOffset.UTC) gives a zoned date-time in UTC.