Java Instant ofEpochMilli()

In this guide, you will learn about the Instant ofEpochMilli() method in Java programming and how to use it with an example.

1. Instant ofEpochMilli() Method Overview

Definition:

The ofEpochMilli() method of the Instant class in Java is used to obtain an instance of Instant using milliseconds from the epoch of 1970-01-01T00:00:00Z.

Syntax:

public static Instant ofEpochMilli(long epochMilli)

Parameters:

- epochMilli: The number of milliseconds from 1970-01-01T00:00:00Z.

Key Points:

- The ofEpochMilli() method is a static method and can be invoked on the Instant class itself.

- It takes as a parameter the number of milliseconds from the epoch of 1970-01-01T00:00:00Z.

- This method can be used to convert a timestamp in milliseconds to an Instant object.

2. Instant ofEpochMilli() Method Example

import java.time.Instant;

public class InstantOfEpochMilliExample {
    public static void main(String[] args) {
        // Creating an Instant from milliseconds from the epoch
        long millisecondsFromEpoch = 1632131130123L; // Example timestamp in milliseconds
        Instant instant = Instant.ofEpochMilli(millisecondsFromEpoch);

        // Displaying the created Instant
        System.out.println("Instant from Epoch Milli: " + instant);
    }
}

Output:

Instant from Epoch Milli: 2021-09-20T09:45:30.123Z

Explanation:

In this example, we have used the ofEpochMilli() method to create an Instant from a given timestamp in milliseconds (1632131130123L). The output displays the created Instant in the ISO-8601 format corresponding to the specified timestamp.

Comments