如何在 Java 中以毫秒为单位获取当前日期/时间?
getTime()Date类的方法检索并返回纪元时间(从1970年1月1日00:00:00GMT0开始的毫秒数。
示例
import java.util.Date;
public class Sample {
public static void main(String args[]){
//实例化Date类
Date date = new Date();
long msec = date.getTime();
System.out.println("毫秒: "+msec);
}
}输出结果毫秒: 1605160094688
getTimeInMillis()日历类的方法从纪元时间(格林威治标准时间1970年1月1日00:00:00)开始检索并返回以毫秒为单位的时间。
示例
import java.util.Calendar;
public class Sample {
public static void main(String args[]){
//创建日历对象
Calendar cal = Calendar.getInstance();
long msec = cal.getTimeInMillis();
System.out.println("毫秒: "+msec);
}
}输出结果毫秒: 1605160934357
toEpochMilli()Instant类的方法返回纪元的毫秒数。
示例
import java.time.Instant;
import java.time.ZonedDateTime;
public class Sample {
public static void main(String args[]){
//创建ZonedDateTime对象
ZonedDateTime obj = ZonedDateTime.now();
Instant instant = obj.toInstant();
long msec = instant.toEpochMilli();
System.out.println("毫秒: "+msec);
}
}输出结果毫秒: 1605162474464