Notes: 01. Understand the Differences Between Legacy Libraries & Date-Time API
This course assumes you know the basics of Kotlin and how to use IntelliJ IDEA. If you’re new to IntelliJ IDEA, read IntelliJ IDEA’s installation guide. If you’re new to Kotlin, check out our Kotlin Apprentice book.
The classes Date
, Calendar
, GregorianCalendar
, TimeZone
, and DateFormat
let you handle every type of date and time using internationalization. However, dealing with these classes, it’s not simple. The main reason is that some of these classes are defined in different packages and follow different guidelines. In the next series of videos, we’ll see how the new library introduced in Java 8 modernizes the way you handle dates. However, you need to know that these legacy classes are the foundations of the new library.
But why do we need a new library? Well, the legacy classes have some issues:
- Classes are mutable, which means we can modify the state of the object after creating it, and they’re not thread-safe. That’s because they’re mutable.
- The API is not ISO 8601 compliant.
- The API is unintuitive. For example, January is represented with the number 0 instead of 1. Also, it doesn’t have a standardization of methods.
But what does ISO 8601 mean?
Well, ISO 8601 is an international standard we use to represent date and time. Let’s take a look at how it works.
2022-11-15T15:32:45.156Z
In the first part of the string, we have the date with the year, the month in second place, and the day in the last third. After the letter T
, which stands for time, there’s, in fact, the time, with the hour, minutes, seconds, and milliseconds. Writing the letter Z
at the end, we’re saying that this date is in UTC.
Now we want to store the Rome time zone inside an IOS 8601. To do that, you can simply substitute the letter Z
with the difference in time of your time zone and then add the time zone name after it. So it’ll become something like this: 2022-11-15T15:32:45.156+01:00[Europe/Rome]
As we said before, the new API provides all the classes with standardization of methods along all the classes of the package. This means every class defines a method with the same name to do one specific thing. Let’s take the method now
, for example. You can call this method inside the classes LocalDate
, ZonedDateTime
, or YearMonth
, and it’ll always return the current moment. Of course, the return type depends on the class that’s calling it.