CodeGym /Courses /Kotlin SELF /Current time and comparisons: Clock.System.now(), sorting...

Current time and comparisons: Clock.System.now(), sorting, and Duration

Kotlin SELF
Level 51, Lesson 2
Available

1. Why we need “current time” and why it’s not a string

When you first want to add time to a program, the usual thought is: “well, I’ll print the text ‘12:34’ and that’s it.” But as soon as questions like “what happened earlier,” “how much time passed,” “sort by time,” or “show the last 10 events” appear, a string stops being your friend and becomes that coworker who “will just hold the cable,” and then disappears along with the cable.

In this lecture we’ll think like this: time is data that can be compared, sorted, and subtracted—not just decoration in the console. For these tasks, kotlinx.datetime gives us Instant (a moment on the timeline), and the Kotlin standard library gives us kotlin.time.Duration (a length of time between moments).

Imagine the timeline as a straight line:

flowchart LR
  A["Instant A"] -->|elapsed| D["Duration"] --> B["Instant B"]

Instant is a “point,” and Duration is the “distance between points.”

2. Clock.System.now(): getting the current Instant

There’s a very human desire: “I need the current time” → “so I’ll just insert Clock.System.now() everywhere.” It’s like cooking: “need salt” → “so I’ll salt at every step.” In the end you either oversalt, or you get an unpredictable taste.

The correct habit is: if “current time” is needed as a reference point, then we take it once and store it in a val. This makes behavior more stable and the code clearer: you can see exactly which “now” you meant.

The simplest scenario: “freeze now”

import kotlinx.datetime.Clock
import kotlinx.datetime.Instant

fun main() {
    val now: Instant = Clock.System.now()
    println(now) // example: 2026-01-14T18:22:10.123Z
}

The output is usually in ISO format. At this stage, what matters is not how it looks, but the fact that it’s an Instant type that you can compare and subtract.

Why calling now() twice yields two different values

import kotlinx.datetime.Clock

fun main() {
    val a = Clock.System.now()
    val b = Clock.System.now()

    println(a == b) // most likely: false
    println(b > a)  // most likely: true
}

Between the two calls, at least a microscopic fraction of time passed. Sometimes it’s so small that you start doubting reality, but the CPU does not.

Good style: “take now once and pass it along”

Suppose we’re creating an event record. It’s better to do this:

import kotlinx.datetime.Clock
import kotlinx.datetime.Instant

fun createTimestamp(): Instant {
    return Clock.System.now()
}

fun main() {
    val createdAt = createTimestamp()
    println(createdAt) // example: 2026-01-14T18:22:10.456Z
}

Yes, it seems “too simple,” but once the code grows, you’ll be grateful that time is obtained in one place instead of being smeared across the whole program like jam on a keyboard.

3. Comparing Instant: earlier/later and checks

Comparisons are where the real advantages of Instant begin. When you have a “moment in time” type, comparisons with >, <, >=, <= become meaningful: you’re comparing points on the time axis, not letters in a string.

In this section we’ll learn to write earlier/later checks, write readable conditions, and treat the idea “time can go backwards” carefully (for example, due to system clock adjustments). We won’t dive deep into the last point, but it’s useful to know it can happen—at least so you won’t be surprised by weird negative durations later.

Check: “the event happened after the program started”

import kotlinx.datetime.Clock

fun main() {
    val startedAt = Clock.System.now()

    // ... some code could be here ...

    val eventAt = Clock.System.now()

    if (eventAt >= startedAt) {
        println("The event happened after start") // most likely this is true
    }
}

The key point here: we’re comparing moments, not local wall-clock time.

Timeout check: “has more than N seconds passed?”

We’re not building any complex timers yet, but this pattern is very common: you want to understand that “enough time” has passed and you can do something (or, conversely, it’s time to stop).

import kotlinx.datetime.Clock
import kotlin.time.Duration.Companion.seconds

fun main() {
    val startedAt = Clock.System.now()

    val now = Clock.System.now()
    val elapsed = now - startedAt

    println(elapsed > 2.seconds) // most often: false
}

This is where Duration appears. For now it’s enough to understand: the difference between two Instant values is a duration.

Nuance: compare the same “now”

Sometimes beginners write a condition like this (and yes, I did too when I was young and compiled faster):

import kotlinx.datetime.Clock
import kotlin.time.Duration.Companion.seconds

fun main() {
    val startedAt = Clock.System.now()

    // Bad idea: now is taken fresh every time
    if (Clock.System.now() - startedAt > 2.seconds) {
        println("More than 2 seconds have passed")
    }
}

Formally it works. Practically it hurts readability: you can’t see where the moment used for the check is “fixed.” It’s better to do val now = ... and use it afterward.

4. The difference between two Instant values as a Duration

When people first hear the word Duration, they often think “oh, it’s like a date, just smaller.” No. A duration is not a “small date,” but a time interval: 5 seconds, 120 milliseconds, 3 minutes. Duration is convenient for measurements: “how long it took,” “how much time passed,” “how late we are.”

In this section we’ll learn how to get a Duration as the difference between two Instant values, extract numbers from it (seconds/milliseconds), and not confuse durations with calendar arithmetic. A calendar is a different beast, and we’re not touching it today.

Basic example: end - start

import kotlinx.datetime.Clock
import kotlin.time.Duration

fun main() {
    val start = Clock.System.now()

    // suppose there was some code here

    val end = Clock.System.now()

    val elapsed: Duration = end - start
    println(elapsed) // example: 12ms
}

Important: elapsed is not a number. It’s a duration object that you can convert to the units you need.

Getting milliseconds, seconds, and nanoseconds

import kotlinx.datetime.Clock

fun main() {
    val start = Clock.System.now()
    val end = Clock.System.now()

    val elapsed = end - start
    println(elapsed.inWholeMilliseconds) // example: 0
    println(elapsed.inWholeNanoseconds)  // example: 50000 (numbers are illustrative)
}

Yes, “0 milliseconds” is a normal result: less than a millisecond may have passed between the two calls.

Negative duration: not a bug, just life

Sometimes (rarely, but it happens) you can get a situation where “the end is earlier than the start”—for example, if the system clock moved. At the basic-course level it’s enough to remember: Duration can be negative, and if you need guarantees, you must design the logic carefully (but that’s a topic of time-measurement architecture, not today’s mechanics).

import kotlin.time.Duration.Companion.seconds

fun main() {
    val d = (-5).seconds
    println(d) // -5s
}

5. Events with time: sorting and a mini example

Once you have a list of events with timestamps, you almost inevitably want: “show the latest,” “sort from newest to oldest,” “find the earliest,” “find the latest.” And this is where Instant suddenly becomes an ideal candidate for sorting, because it’s comparable: Instant has a natural order “earlier → later.”

In this section we’ll apply familiar list-sorting functions, but to moments in time. We’ll use sorted(), sortedDescending(), sortedBy { ... }, and friends. These functions in the standard library build a new list and do not mutate the original, which makes the code more predictable.

Sorting a list of Instant

import kotlinx.datetime.Instant

fun main() {
    val moments = listOf(
        Instant.parse("2026-01-06T10:00:01Z"),
        Instant.parse("2026-01-06T10:00:00Z"),
        Instant.parse("2026-01-06T09:59:59Z")
    )

    val sorted = moments.sorted()
    println(sorted)
}

Here we use Instant.parse(...) purely as a quick way to get test moments. In a real application, you’ll more often have live Clock.System.now() values.

Sorting “newest first”

import kotlinx.datetime.Instant

fun main() {
    val moments = listOf(
        Instant.parse("2026-01-06T10:00:01Z"),
        Instant.parse("2026-01-06T10:00:00Z")
    )

    println(moments.sortedDescending()) // the later moment comes first
}

Meaning: if an Instant represents a moment, then “greater” means “later.”

Sorting objects by the createdAt field

Now let’s take a step closer to an application. Suppose we have records (for example, expenses), and each has a creation time.

import kotlinx.datetime.Instant

data class Expense(
    val title: String,
    val amount: Int,
    val createdAt: Instant
)

Then the sorting looks like this:

import kotlinx.datetime.Instant

data class Expense(val title: String, val amount: Int, val createdAt: Instant)

fun main() {
    val xs = listOf(
        Expense("Coffee", 250, Instant.parse("2026-01-06T10:00:00Z")),
        Expense("Pizza", 900, Instant.parse("2026-01-06T09:00:00Z"))
    )

    val sorted = xs.sortedBy { it.createdAt }
    println(sorted.map { it.title }) // [Pizza, Coffee]
}

Functions like sortedBy() are a standard style: we sort a list by a key.

Mini practical example: adding time to an expense tracker

Now comes the important “why all this.” In learning examples it’s easy to feel like Instant is just a new type that prints a pretty string. But the real power starts when you add time to the application state and begin building logic: sorting, “the last expense was N minutes ago,” “show the last 5.”

In this mini example we’ll take a simple “expense” model and add a createdAt: Instant field, filled via Clock.System.now(). This doesn’t require new architectural tricks: just one more field, but it immediately unlocks many possibilities.

Expense creation function “right now”

import kotlinx.datetime.Clock
import kotlinx.datetime.Instant

data class Expense(val title: String, val amount: Int, val createdAt: Instant)

fun createExpenseNow(title: String, amount: Int): Expense {
    val now = Clock.System.now()
    return Expense(title = title, amount = amount, createdAt = now)
}

Notice the style: take now once so that the “creation moment” is exactly one moment, not “slightly changing while the constructor was thinking.”

Add an expense to a list and print

import kotlinx.datetime.Clock
import kotlinx.datetime.Instant

data class Expense(val title: String, val amount: Int, val createdAt: Instant)

fun main() {
    val expenses = mutableListOf<Expense>()

    expenses.add(Expense("Coffee", 250, Clock.System.now()))
    expenses.add(Expense("Metro", 60, Clock.System.now()))

    println(expenses.size) // 2
}

We use MutableList because we add elements. The fact that the collection is mutable does not require var: you can change the contents even of a val, because val protects the reference, not the internals of the object.

“Latest expenses”: sort by time and take(n)

We won’t dive into “top-N” as a separate topic, but the technique is very natural: first sort by time, then take the first few.

import kotlinx.datetime.Instant

data class Expense(val title: String, val amount: Int, val createdAt: Instant)

fun latest(expenses: List<Expense>, n: Int): List<Expense> {
    return expenses
        .sortedByDescending { it.createdAt }
        .take(n)
}

Sorting here returns a new list and does not change the original, which reduces the number of “unexpected surprises” when reading code.

“How much time has passed since the last expense?”

This is where Duration shows itself as maximally practical.

import kotlinx.datetime.Clock
import kotlinx.datetime.Instant
import kotlin.time.Duration

data class Expense(val title: String, val amount: Int, val createdAt: Instant)

fun timeSinceLast(expenses: List<Expense>): Duration? {
    val last = expenses.maxByOrNull { it.createdAt } ?: return null
    return Clock.System.now() - last.createdAt
}

The contract is simple: if there are no expenses, return null; otherwise return the duration from the last event to the current moment.

And an example of use:

import kotlinx.datetime.Clock
import kotlinx.datetime.Instant

data class Expense(val title: String, val amount: Int, val createdAt: Instant)

fun main() {
    val xs = listOf(
        Expense("Coffee", 250, Clock.System.now())
    )

    val d = Clock.System.now() - xs[0].createdAt
    println(d.inWholeSeconds) // most likely: 0
}

6. Common mistakes

Mistake #1: calling Clock.System.now() many times and thinking it’s “the same now.”
If you take now() in several places in a row, you get several different moments in time. Sometimes the difference is microscopic, but logically it’s already “different timestamps.” Good style is to take val now = Clock.System.now() once within the operation and use it afterward.

Mistake #2: confusing Duration with “calendar” shifts.
Duration is “how much time passed,” not “add one calendar day.” Even if a duration equals 24 hours, that still doesn’t mean “the next date” in the calendar sense, because calendar rules live separately from durations. For measurement tasks, stick to Instant + Duration, and don’t try to imitate calendar stuff with durations.

Mistake #3: sorting events by time strings instead of Instant.
Once you store time as a string and do sorted() on strings, you start relying on formatting and data discipline. That’s too fragile. With Instant, sorting works by meaning and uses the natural time order.

Mistake #4: “accidentally mutating” the original list while sorting.
In Kotlin there are sorts that return a new list (sorted*), and there are in-place sorts for MutableList. At the beginning it’s simpler and safer to stick to “produce a new list,” because it reduces side effects: the original data stays as it was, and the sorted version is a separate result.

Mistake #5: trying to measure time via String/split/“manual parsing.”
If you catch yourself thinking “I’ll parse hours and minutes from a string and subtract,” stop. This almost guarantees bugs at boundaries (minutes roll over 60, days roll over months, and so on). For measurements, use the difference between Instant values, which immediately gives you a Duration.

Mistake #6: assuming Duration is a number and losing the unit.
Duration carries the meaning “duration” and lets you safely convert it to the units you need (inWholeMilliseconds, inWholeSeconds). If you immediately convert it to a Long and forget whether it was seconds or milliseconds, a week later you’ll get a bug “1000x slower/faster”—a classic, almost like a forgotten break in a when in languages where it exists at all.

1
Task
Kotlin SELF, level 51, lesson 2
Locked
One timestamp
One timestamp
1
Task
Kotlin SELF, level 51, lesson 2
Locked
Which is earlier
Which is earlier
1
Task
Kotlin SELF, level 51, lesson 2
Locked
Enter Stopwatch
Enter Stopwatch
1
Task
Kotlin SELF, level 51, lesson 2
Locked
Activity feed
Activity feed
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION