Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of new Date().getTime() in Java 8

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.

like image 295
Michal Kordas Avatar asked Sep 10 '19 11:09

Michal Kordas


People also ask

What does date () getTime () do in Java?

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.

What is new date () in Java?

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.

What does getTime () mean?

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.

What is the feature of the new date and time API in Java 8?

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.


1 Answers

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

like image 139
Marteng Avatar answered Oct 08 '22 08:10

Marteng