如何在 Java 中获得时间(1970-01-01)的毫秒?

我需要得到 Java 中从1970-01-01 UTC 到现在 UTC 的毫秒数。

我还希望能够得到从1970-01-01世界协调时到任何其他世界协调时日期时间的毫秒数。

155002 次浏览

How about System.currentTimeMillis()?

From the JavaDoc:

Returns: the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC

Java 8 introduces the java.time framework, particularly the Instant class which "...models a ... point on the time-line...":

long now = Instant.now().toEpochMilli();

Returns: the number of milliseconds since the epoch of 1970-01-01T00:00:00Z -- i.e. pretty much the same as above :-)

Cheers,

Also try System.currentTimeMillis()

java.time

Using the java.time framework built into Java 8 and later.

import java.time.Instant;


Instant.now().toEpochMilli(); //Long = 1450879900184
Instant.now().getEpochSecond(); //Long = 1450879900

This works in UTC because Instant.now() is really call to Clock.systemUTC().instant()

https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html

You can also try

  Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTimeInMillis());

getTimeInMillis() - the current time as UTC milliseconds from the epoch