How do I get milliseconds from epoch (1970-01-01) in Java?

JavaDate

Java Problem Overview


I need to get the number of milliseconds from 1970-01-01 UTC until now UTC in Java.

I would also like to be able to get the number of milliseconds from 1970-01-01 UTC to any other UTC date time.

Java Solutions


Solution 1 - Java

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,

Solution 2 - Java

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

Solution 3 - Java

Also try System.currentTimeMillis()

Solution 4 - Java

You can also try

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaulGView Question on Stackoverflow
Solution 1 - JavaAnders R. BystrupView Answer on Stackoverflow
Solution 2 - JavaPrzemekView Answer on Stackoverflow
Solution 3 - JavaAlexander PavlovView Answer on Stackoverflow
Solution 4 - JavaHari RaoView Answer on Stackoverflow