如何在 Java 中获取当前日期/时间的毫秒数?
Date 类的 getTime() 方法用于检索并返回纪元时间(距离 1970 年 1 月 1 日 00:00:00 GMT0 的毫秒数)。
示例
import java.util.Date;
public class Sample {
public static void main(String args[]){
//Instantiating the Date class
Date date = new Date();
long msec = date.getTime();
System.out.println("Milli Seconds: "+msec);
}
}输出
Milli Seconds: 1605160094688
Calendar 类的 getTimeInMillis() 方法用于检索并返回 epoch 纪元时间(1970 年 1 月 1 日 00:00:00 GMT)的毫秒数。
示例
import java.util.Calendar;
public class Sample {
public static void main(String args[]){
//Creating the Calendar object
Calendar cal = Calendar.getInstance();
long msec = cal.getTimeInMillis();
System.out.println("Milli Seconds: "+msec);
}
}输出
Milli Seconds: 1605160934357
Instant 类的 toEpochMilli() 方法返回自 epoch 纪元以来的毫秒数。
示例
import java.time.Instant;
import java.time.ZonedDateTime;
public class Sample {
public static void main(String args[]){
//Creating the ZonedDateTime object
ZonedDateTime obj = ZonedDateTime.now();
Instant instant = obj.toInstant();
long msec = instant.toEpochMilli();
System.out.println("Milli Seconds: "+msec);
}
}输出
Milli Seconds: 1605162474464
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP