How can you convert time to a timestamp in Java?

In Java, the Instant class can be used to convert time to a timestamp. Instant class represents a specific point on the timeline, you can obtain the current time’s Instant object by using Instant.now() method, and then convert the time to milliseconds timestamp by calling its toEpochMilli() method.

The sample code is provided below:

import java.time.Instant;

public class Main {
    public static void main(String[] args) {
        Instant now = Instant.now();
        long timestamp = now.toEpochMilli();
        System.out.println("当前时间戳:" + timestamp);
    }
}

Running the above code will output the current timestamp.

bannerAds