Reputation: 55
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.
Upvotes: 0
Views: 1612
Reputation: 86223
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.
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:
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.Upvotes: 7