95

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,040,783
  • 362
  • 3,548
  • 3,513
PaulG
  • 6,689
  • 10
  • 51
  • 95

4 Answers4

188

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,

Anders R. Bystrup
  • 15,324
  • 10
  • 61
  • 54
  • 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
55

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
  • 21,021
  • 11
  • 69
  • 118
Przemek
  • 6,442
  • 3
  • 39
  • 51
17

Also try System.currentTimeMillis()

Alexander Pavlov
  • 30,691
  • 5
  • 65
  • 91
-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,580
  • 3
  • 19
  • 31
  • 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