Before Java 8 I was using in code new Date().getTime()
to obtain current timestamp as number. Can I assume that Instant.now().toEpochMilli()
is safe equivalent to the legacy way? Does it have exactly the same behavior and similar performance characteristics? Are there any better alternatives?
I want to use the Java 8 way in ecosystem where all surrounding components still use new Date().getTime()
, so produced results must be consistent.
The getTime() method of Java Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GTM which is represented by Date object.
Date() : Creates date object representing current date and time. Date(long milliseconds) : Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
The getTime() method returns the number of milliseconds since the ECMAScript epoch. You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method.
The new date-time API is immutable and does not have setter methods. Poor design − Default Date starts from 1900, month starts from 1, and day starts from 0, so no uniformity. The old API had less direct methods for date operations. The new API provides numerous utility methods for such operations.
All of Instant.now().toEpochMilli()
, new Date().getTime()
and System.currentTimeMillis()
will give you the number of milliseconds since epoch.
From CPU power and memory allocation point of view, you should use System.currentTimeMillis()
because it's a native method that delegates the task to the underlying operating system (this calculation usually is very optimized and doesn't require garbage collection etc).
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