minus

operator fun minus(duration: Duration): Instant(source)

Returns an instant that is the result of subtracting the specified duration from this instant.

If the duration is positive, the returned instant is earlier than this instant. If the duration is negative, the returned instant is later than this instant.

The return value is clamped to the boundaries of Instant if the result exceeds them.

Pitfall: Duration.Companion.days are multiples of 24 hours, but in some time zones, some days can be shorter or longer because clocks are shifted. Consider using kotlinx-datetime for arithmetic operations that take time zone transitions into account.

Since Kotlin

2.1

Samples

import kotlin.test.*
import kotlin.time.*
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.nanoseconds

fun main() { 
   //sampleStart 
   // Finding a moment that's earlier than the starting point by the given amount of real time
val instant = Instant.fromEpochSeconds(7 * 60 * 60, nanosecondAdjustment = 123_456_789)
val fiveHoursEarlier = instant - 5.hours
println(fiveHoursEarlier.epochSeconds == 2 * 60 * 60L) // true
println(fiveHoursEarlier.nanosecondsOfSecond == 123_456_789) // true 
   //sampleEnd
}

operator fun minus(other: Instant): Duration(source)

Returns the Duration between two instants: other and this.

The duration returned is positive if this instant is later than the other, and negative if this instant is earlier than the other.

The result is never clamped, but note that for instants that are far apart, the value returned may represent the duration between them inexactly due to the loss of precision.

Note that sources of Instant values (in particular, Clock) are not guaranteed to be in sync with each other or even monotonic, so the result of this operation may be negative even if the other instant was observed later than this one, or vice versa. For measuring time intervals, consider using TimeSource.Monotonic.

Since Kotlin

2.1

Samples

import kotlin.test.*
import kotlin.time.*
import kotlin.time.Duration.Companion.hours
import kotlin.time.Duration.Companion.nanoseconds

fun main() { 
   //sampleStart 
   // Finding the difference between two instants in terms of elapsed time
val instant1 = Instant.fromEpochSeconds(0) // The Unix epoch start.
val instant2 = Instant.fromEpochSeconds(7 * 60 * 60) // 7 hours since the Unix epoch.
val elapsedTime = instant1 - instant2 // The duration between instant1 and instant2.
println(elapsedTime == (-7).hours) // true 
   //sampleEnd
}