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.
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.
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 .
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,
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With