ofEpochMilli() and Millisecond Precision
You'll learn how to create Instant objects from millisecond-based timestamps, bridging modern Java time APIs with legacy code.
Why Milliseconds Matter
Many legacy Java APIs and system libraries use milliseconds since the epoch (January 1, 1970, 00:00:00 UTC) to represent time. System.currentTimeMillis(), Date.getTime(), and database timestamps often return values in this format. The ofEpochMilli() method lets you convert these millisecond timestamps into modern Instant objects.
Creating Instants from Milliseconds
While ofEpochSecond() works with seconds, ofEpochMilli() accepts millisecond precision:
// From legacy APIs that return milliseconds
long millis = System.currentTimeMillis();
Instant instant = Instant.ofEpochMilli(millis);
// From a specific millisecond timestamp
Instant specific = Instant.ofEpochMilli(1609459200000L); // Jan 1, 2021
Understanding the Precision
Think of milliseconds like measuring distance in millimeters instead of meters—you get three additional decimal places of precision. One second equals 1,000 milliseconds, so ofEpochMilli(5000) equals ofEpochSecond(5).
// These create equivalent Instants
Instant fromSeconds = Instant.ofEpochSecond(10);
Instant fromMillis = Instant.ofEpochMilli(10000);
// Both represent 10 seconds after epoch
Real-World Use Case
When integrating with older code that stores timestamps as long millisecond values, ofEpochMilli() provides seamless conversion:
// Legacy database returns millisecond timestamp
long dbTimestamp = 1672531200000L;
Instant recordCreated = Instant.ofEpochMilli(dbTimestamp);
// Now you can use modern java.time operations
Key Takeaway: ofEpochMilli() bridges the gap between legacy millisecond-based timestamps and modern Instant objects, enabling interoperability with older APIs while maintaining millisecond precision.