104

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
PaulG
  • 6,920
  • 12
  • 54
  • 98

4 Answers4

202

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 :-)

starball
  • 20,030
  • 7
  • 43
  • 238
Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
  • 3
    As this answer was 2012 and Java 8 was not around it is a good one. Equally good is the java.time answer from Prezemek. That considers the current Java 8 java.time framework. – Zack Jannsen Feb 18 '16 at 13:03
  • 1
    For Edification: I tested a couple of ways to get a UTC time in Milliseconds and found java.time.Instant.now().toEpochMilli to work well. I compared this to ZonedDateTime.now(ZoneOffset.UTC) method options (which I have seen in other posts as options) and as expected, the Java.time.Instant.now() approach was a little faster on my machine ... low single digit milliseconds on thirty consecutive runs. – Zack Jannsen Feb 18 '16 at 13:12
  • Remember also that `System.currentTimeInMs()` does not update every millisecond! – Caveman Nov 15 '18 at 15:04
59

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

Hack-R
  • 22,422
  • 14
  • 75
  • 131
Przemek
  • 7,111
  • 3
  • 43
  • 52
17

Also try System.currentTimeMillis()

Alexander Pavlov
  • 31,598
  • 5
  • 67
  • 93
-2

You can also try

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

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

Hari Rao
  • 2,990
  • 3
  • 21
  • 34
  • 3
    This terrible date-time class was supplanted years ago by the modern *java.time* classes defined by JSR 310. See modern solution in Answers by Bystrup & Hack-R – Basil Bourque Sep 02 '19 at 16:31
  • 1
    Modern solution using `java.time.Instant` seen in [this Answer](https://stackoverflow.com/a/13731260/642706) and [this Answer](https://stackoverflow.com/a/34437574/642706) – Basil Bourque Sep 02 '19 at 23:08