Course contentsShow
← Java
Lesson 1831 of 2,87038. Date and Time API (java.time)Free lesson

Retrieving Epoch Values: getEpochSecond() and toEpochMilli()

Extract epoch timestamps from Instant objects for interoperability with timestamp-based systems.

Retrieving Epoch Values: getEpochSecond() and toEpochMilli()

What you'll learn: How to extract numeric timestamps from Instant objects for use with timestamp-based systems and APIs.

Why Extract Epoch Values?

You've learned to create Instant objects from epoch values, but often you need to go the other direction—converting an Instant back into a numeric timestamp. This is essential when interfacing with databases, logging systems, or APIs that work with raw timestamp numbers rather than date-time objects.

Think of it like converting currency: you can deposit money into your bank account (creating an Instant), but sometimes you need to withdraw it as cash (extracting the epoch value) to use in systems that only accept numeric payments.

The Two Extraction Methods

Instant provides two methods for retrieving epoch timestamps at different precision levels:

getEpochSecond() returns the number of seconds since January 1, 1970, 00:00:00 UTC as a long. This is the standard Unix timestamp format.

toEpochMilli() returns the number of milliseconds since the epoch as a long. This provides millisecond precision, which many modern systems require.

Instant now = Instant.now();

long seconds = now.getEpochSecond();      // e.g., 1704067200
long millis = now.toEpochMilli();          // e.g., 1704067200000

// Converting between them
long millisFromSeconds = seconds * 1000;   // Add three zeros
long secondsFromMillis = millis / 1000;    // Remove three zeros

Practical Applications

These methods are invaluable when logging timestamps, storing values in databases that use numeric timestamp columns, or communicating with REST APIs that expect epoch values in JSON payloads.

Key Takeaway: Use getEpochSecond() for second-precision timestamps and toEpochMilli() for millisecond-precision timestamps when you need to convert Instant objects to numeric values for interoperability with external systems.