Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

date

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.

like image 862
PaulG Avatar asked Dec 05 '12 19:12

PaulG


People also ask

How do you find milliseconds from a Date object?

Once you have the Date object, you can get the milliseconds since the epoch by calling Date. getTime() . The full example: String myDate = "2014/10/29 18:10:45"; //creates a formatter that parses the date in the given format SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = sdf.

How do you convert datetime to milliseconds?

A simple solution is to get the timedelta object by finding the difference of the given datetime with Epoch time, i.e., midnight 1 January 1970. To obtain time in milliseconds, you can use the timedelta. total_seconds() * 1000 .


2 Answers

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,

like image 172
Anders R. Bystrup Avatar answered Oct 12 '22 01:10

Anders R. Bystrup


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

like image 23
Przemek Avatar answered Oct 11 '22 23:10

Przemek