Home > Net >  How to correctly work with dates on Android
How to correctly work with dates on Android

Time:10-27

I'm working on a Android project with Kotlin where we need to perform validations on dates both from the device and from our backend. So far we've been working with the Date class to represent dates, the SimpleDateFormat class to parse strings and format dates and the Calendar class to perform operations on dates such as getting the date from x days ago and stuff like that. I've come accross some resources that state that the correct way to work with dates is to use the java.time package (classes such as LocalDateTime, LocalTime, etc.). I'm interested in knowing exactly what should be the correct way to work with dates (from parsing to formatting) and if I need to take into account timezones. I've seen similar questions but none of them really summarizes what I'd like to know.

CodePudding user response:

The correct way of working

To work correctly with dates and times requires that you understand something about what dates and times are and how they behave in the real life of your users. Working correctly is not about using this or the other library class. Depending on the work you do you will need to know about leap years, and/or the Julian, the Gregorian and the proleptic Gregorian calendar and/or many different solar and lunar calendar systems.

To work correctly with times there is hardly a way to avoid taking time zone into account. For an introduction to time zones I recommend the video that I link to at the bottom. It’s entertaining and explains the basics well.

The recommended library classes to use

It’s definitely recommended to use java.time, the modern Java date and time API, for your date and time work. Compared to the outdated date and time classes from Java 1.0 and 1.1 some differences are:

  • The old classes pretend that some things are simple that really are not simple, some programmers do not realize the complexity of correct date and time handling and leave errors in their code that go undetected. The modern classes in many cases force the programmer to decide what we want, leaving much less room for unintentional errors. We must decide whether we want a date or a time or both, which time zone we want, etc., etc.
  • Along the same line the old classes pretend that dates and times are the same and can be considered with or without time zones, which is not true. Believing it will cause all kinds of errors in corner cases. Using java.time you need to choose between LocalDate, Instant, ZonedDateTime and many other date-time classes, which may feel a hassle at first, but which will make your code clearer and improve the chances that it is also correct.
  • In many cases the old classes accept garbage input/arguments, again allowing obvious errors to go undetected. The modern classes do a much greater job of validation.
  • The old classes generally aren’t thread-safe. The modern ones are.

Links

  • Related