How can we convert time to a timestamp in Java?

In Java, you can use the java.util.Date class and java.sql.Timestamp class to convert time to a timestamp.

Here is a sample code demonstrating how to convert the current time to a timestamp.

import java.util.Date;

public class TimeStampExample {
    public static void main(String[] args) {
        // 获取当前时间
        Date date = new Date();

        // 将时间转换为时间戳(毫秒)
        long timestamp = date.getTime();

        // 输出时间戳
        System.out.println("时间戳:" + timestamp);
    }
}

The getTime() method in the above code returns the number of milliseconds since January 1, 1970, known as a timestamp.

Note: The java.util.Date class has been deprecated in Java 8, it is recommended to use classes from the java.time package to handle dates and times. Here is an example code using the java.time.Instant class to convert time to a timestamp.

import java.time.Instant;

public class TimeStampExample2 {
    public static void main(String[] args) {
        // 获取当前时间
        Instant instant = Instant.now();

        // 将时间转换为时间戳(毫秒)
        long timestamp = instant.toEpochMilli();

        // 输出时间戳
        System.out.println("时间戳:" + timestamp);
    }
}

In this example, the Instant.now() method returns the current timestamp and the toEpochMilli() method converts the time to a timestamp in milliseconds.

bannerAds