Wrangling Dates & Time in Android

Dec 15 2022 · Kotlin 1.6.21, Android 13, IntelliJ 2022.1

Part 1: Wrangling Dates & Time in Android

05. Localize With ZonedDateTime

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 04. Store Dates & Times Using Date Classes Next episode: 06. Choose Between ZonedDateTime & Instant

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 05. Localize With ZonedDateTime

You can think of ZonedDateTime as an Instant combined with a ZoneId.

This class lets you catch the current moment associated with a specific region called the time zone. This means you’re using UTC to get the current moment. This class plays an essential role in the Data-Time library. That’s because one of the best practices in development is to handle nearly all of your backend, database, business logic, data persistence, and data exchange in UTC. Once you save the value in UTC you can then show it to the user, adjusting the time using with their time zone. Let’s find out how to do this in code.

To obtain the current moment in time, as usual, we call the now function. Let’s write:

val zdt = ZonedDateTime.now()

And print it:

println("zdt: $zdt")

You can see that beyond a time and date, the instance also defines a specific region, which in my case is Rome. We can also get a moment in time from another region. You can pass the region you picked inside the now method. For example, let’s say we want to get the current moment in time in Amsterdam. First, let’s define a ZoneId:

val amsterdamZone = ZoneId.of("Europe/Amsterdam")

And now we can pass it inside the now method:

val localizedZdt = ZonedDateTime.now(amsterdamZone)

Let’s print and run the code:

println("localizedZdt: $localizedZdt")

We can apply the same logic to a LocalDateTime object and turn it into a ZonedDateTime object. The only thing we need to do is passing a ZoneId to convert the date into our time zone.

Let’s say we have booked an appointment with our doctor for the 23rd of October 2023 at 11 am. First, we need to create a LocalDateTime object. So:

val doctorAppointment = LocalDateTime.of(2023, Month.OCTOBER, 23, 11, 0)

Now we need to turn it into a ZonedDateTime object. To do so we can call atZone on doctorAppointment. So:

val doctorCurrentZoned = doctorAppointment.atZone(ZoneId.systemDefault())

Notice that ZoneId.systemDefault() gets the device’s time zone. For me, it’ll be Rome. Let’s print and run the code:

println("doctorInstantAppointment: $doctorCurrentZoned")