Java System.currentTimeMillis()

Working with Unix timestamps in Java using System.currentTimeMillis(), Instant, and the java.time API. Includes conversions and best practices.

Language

System.currentTimeMillis()

Detailed Explanation

Java provides several ways to work with Unix timestamps, ranging from the legacy System.currentTimeMillis() to the modern java.time API introduced in Java 8. Understanding both is essential because legacy codebases still use the older approach extensively.

Getting the current timestamp:

// Milliseconds since epoch (legacy approach)
long ms = System.currentTimeMillis();   // 1700000000000L

// Seconds since epoch (java.time)
long sec = Instant.now().getEpochSecond();  // 1700000000L

// Milliseconds (java.time)
long ms2 = Instant.now().toEpochMilli();    // 1700000000000L

Converting between timestamps and dates:

// Timestamp to Instant
Instant instant = Instant.ofEpochSecond(1700000000L);
Instant instantMs = Instant.ofEpochMilli(1700000000000L);

// Instant to ZonedDateTime
ZonedDateTime zdt = instant.atZone(ZoneId.of("America/New_York"));

// Formatting
String iso = instant.toString();  // "2023-11-14T22:13:20Z"
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String formatted = zdt.format(fmt);

Legacy Date class (avoid in new code):

// Old approach — still seen everywhere
Date date = new Date(1700000000000L);  // expects milliseconds
long timestamp = date.getTime();

// Converting between old and new
Instant fromDate = date.toInstant();
Date fromInstant = Date.from(instant);

Common pitfalls:

Java's System.currentTimeMillis() returns milliseconds, not seconds. This trips up developers coming from Python or C. Additionally, the legacy java.util.Date class is mutable and not thread-safe — another reason to prefer Instant and the java.time API.

Nano-precision: Java's Instant supports nanosecond precision internally, though System.currentTimeMillis() only provides millisecond granularity. For higher resolution, use Instant.now() on JDK 9+ where the default clock provides microsecond precision on most platforms. For benchmarking, use System.nanoTime() which measures elapsed time independent of wall-clock adjustments.

Use Case

Java timestamps are critical in enterprise systems for generating transaction IDs, setting cache eviction policies, and computing token lifetimes in OAuth 2.0 authorization servers.

Try It — Timestamp Converter

Open full tool