Until now, we’ve learned to work with date-time library classes. You know when you should use each class and how to use it. Now it’s time to work on the appearance and localization of your dates.
In this lesson, we’ll look into the format package that helps you format and parse dates and times.
The format package has 2 main goals:
- Parsing is nothing more than interpreting a string with the possibility of turning it into a time or date object.
- Formatting means turning the date or time object into a readable and localized string we are used to seeing every day.
Let’s implement them.
To parse dates, simply use the parse method built into the class LocalDate passing the date and the right ISO for your date. For instance, when you write:
val date = "1902-07-22"
The year, month, and day follow an order, and they’re divided with a dash.
To parse this date we can use the ISO_LOCAL_DATE in this way:
val localDate = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE)
We can print it and see that parsing has been successful.
println("LocalDate: $localDate")
We can also make the inverse, that is formatting a date, by saying:
val currentData1 = DateTimeFormatter.ISO_LOCAL_DATE.format(LocalDate.now())
When we print it we get our date in the same format:
println("currentData1: $currentData1")
You can get the exact same result calling the format method from the LocalDate instance in this way:
val currentData2 = LocalDate.now().format(DateTimeFormatter.ISO_LOCAL_DATE)
println("currentData2: $currentData2")
To format based on a location, we’ll need again the DateTimeFormatter. In fact, this class is the only thing you need to format dates and times. It’s the Sheldon Cooper of formatting.
Let’s format a date using the France localization.
val localizedDtf = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.FRANCE)
The method ofLocalizedDate defines how many details the date should contain. In this case, we chose MEDIUM, but there’s also SHORT, LONG, and FULL.
Now we can localize the current date and print it:
val localizedDtfFormatted = localizedDtf.format(LocalDate.now())
println("localizedDtfFormatted: $localizedDtfFormatted")
You can go through the exact same process to localize a time using the class LocalTime.
If you don’t fit in any of the pre-built format stiles, you can create your own. To create a custom pattern, use the method ofPattern. So:
val customDtf = DateTimeFormatter.ofPattern("MMM/dd/yy hh:mm a")
And now we do the exact same thing as we did before:
val customFormattedDate = customDtf.format(LocalDateTime.now())
println("customFormattedDate: $customFormattedDate")