I have been building out an app and to save important time information I have been using System.currentTimeMillis()
to get the timestamps in ms. All my algorithms use this ms data and dates are saved with this ms data. Also duration of cache is determined and object dates are formatted from this millisecond timestamp.
I am unsure if this is a good practice though. Is it better to use Calendar.getinstace()
I have gathered that currentTimeMillis() could be a bad practice as it can lead to inconsistencies in the time data but I don't understand why this is.
Calendar is always bad practice.
Java has 3 to 4 APIs for time. In order of introduction:
java.util.Date
and sometime later, java.sql.Timestamp
and Date. This is very bad API; at this point, almost all the methods in these are deprecated because they are misleading or straight up do not do what they suggest they do, and are in any case gigantic misnomers. j.u.Date
represents an instant in time, not readily representable in human terms. Dates are fundamentally human concepts.java.time
. THIS is the good one. This has few surprises, is complex where time ends up being actually complex, the types are properly named, going so far as having both j.t.Instant
and j.t.ZonedDateTime
, and you can express virtually anything date-related.I'd say using either j.u.Date or Calendar is strongly dis-recommended. If all you're doing is measuring instants in time, feel free to stick with System.currentTimeMillis() - but if ever you need to print that in human form (such as: "On 2020-07-20 at 16:34, this happened"), switch to java.time
instead. If you prefer, feel free to ditch currentTimeMillis and use j.t.Instant
for those purposes instead - your preference.