Two options
Instant.now().toEpochMilli()
, as you said
System.currentTimeMillis()
as Andy Turner and Marteng said
The choice between the two a matter of taste. Instant
is the modern replacement for Date
and to many the natural choice. Use it if you want to give a modern impression. System.currentTimeMillis()
is as old as Date
. While Date
is decidedly poorly designed and should be avoided always, I am not aware of any design problems with System.currentTimeMillis()
.
Even more modern: keep the Instant
Using a long
to represent a point in time is very low-level and hard to debug because we don’t naturally assign any meaning to the number. If you can, instead of keeping a number, keep an Instant
. It also gives you an even finer resolution than milliseconds (since Java 9 Instant.now()
has a precision of microseconds on many platforms).
Safe and performant?
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?
Yes, it is safe and equivalent and has similar performance characteristics.
Only under all circumstances avoid Date
and Calendar
. They are poorly designed and long outdated and have modern replacements.
System.currentTimeMillis()
it's old but probably the same that the other classes are using – RoughshodSystem.currentTimeMillis()
. – SeifInstant instantFromDate = new Date().toInstant()
too ;-) – Gallery