javaandroidjava-calendar

currentTimeMillis vs Calendar


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.


Solution

  • Calendar is always bad practice.

    Java has 3 to 4 APIs for time. In order of introduction:

    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.