如何在 Java 中从 epoch (1970-01-01) 获取毫秒数?java.time
我需要获取 Java 中从 1970-01-01 UTC 到现在的 UTC 的毫秒数。
我还希望能够获得从 1970-01-01 UTC 到任何其他 UTC 日期时间的毫秒数。
我需要获取 Java 中从 1970-01-01 UTC 到现在的 UTC 的毫秒数。
我还希望能够获得从 1970-01-01 UTC 到任何其他 UTC 日期时间的毫秒数。
System.currentTimeMillis()怎么样
?
来自 JavaDoc:
返回:当前时间与 1970 年 1 月 1 日 UTC 午夜之间的差值(以毫秒为单位)
Java 8 引入了 java.time
框架,特别是 Instant
类,它“...模型一个 ...时间线上的点...“:
long now = Instant.now().toEpochMilli();
返回:自 1970-01-01T00:00:00Z 纪元以来的毫秒数 -- 即几乎与上述相同 :-)
干杯
使用 Java 8 及更高版本中内置的 java.time
框架。
import java.time.Instant;
Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900
这在 UTC 中有效,因为实际上调用Instant.now()
Clock.systemUTC().instant()
https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html