Wrangling Dates & Time in Android

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

Part 1: Wrangling Dates & Time in Android

02. Work With Instant

Episode complete

Play next episode

About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 01. Understand the Differences Between Legacy Libraries & Date-Time API Next episode: 03. Use Duration, Period & ChronoUnit to Calculate Time

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.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

[Slide 01 - Composition of an Instant] [//]

Current Instant

As the first thing, let’s define an Instant. To do that we can simply use the static method now. In this way, you get the current moment in time. So let’s write:

val currentInstant = Instant.now()
println("currentInstant: $currentInstant")

Adding and Subtracting Time

Instant also provides methods to perform calculations. For example, we can add 10 hours to currentInstant. So let’s define another instance, which we call inTenHours.

val inTenMinutes = currentInstant.plus(10, ChronoUnit.HOURS)

Comparing two Dates

The Instant class defines other methods including isAfter. As you can imagine this function tells you what date is the most recent one. We can test this method on our previous instances. So write:

val isCurrentInstantAfterEpoch = currentInstant.isAfter(inTenHours)

Parsing a Date and Making Calculations

Another interesting method is until. If you want to know how many days you’ve lived till now this is the method for you. First, you need to parse the date of your birthday. For this example we’ll take Marco as our case study. Marco was born on the 21 of December 2000.

val dateOfBirth = Instant.parse("2000-12-21T09:00:00.00Z")
val daysSinceBirth = dateOfBirth.until(Instant.now(), ChronoUnit.DAYS)
println("daysSinceBirth: $daysSinceBirth")