minus
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 platform-specific boundaries for Instant if the result exceeds them.
Pitfall: Duration.Companion.days are multiples of 24 hours and are not calendar-based. Consider using the minus overload that accepts a multiple of a DateTimeUnit instead for calendar-based operations instead of using Duration. For an explanation of why some days are not 24 hours, see DateTimeUnit.DayBased.
Samples
import kotlinx.datetime.*
import kotlinx.datetime.format.*
import kotlin.random.*
import kotlin.test.*
import kotlin.time.Duration.Companion.hours
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
check(fiveHoursEarlier.epochSeconds == 2 * 60 * 60L)
check(fiveHoursEarlier.nanosecondsOfSecond == 123_456_789)
//sampleEnd
}
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.
Samples
import kotlinx.datetime.*
import kotlinx.datetime.format.*
import kotlin.random.*
import kotlin.test.*
import kotlin.time.Duration.Companion.hours
fun main() {
//sampleStart
// Finding the difference between two instants in terms of elapsed time
check(Instant.fromEpochSeconds(0) - Instant.fromEpochSeconds(epochSeconds = 7 * 60 * 60) == (-7).hours)
//sampleEnd
}