periodUntil

expect fun Instant.periodUntil(other: Instant, timeZone: TimeZone): DateTimePeriod(source)

Returns a DateTimePeriod representing the difference between this and other instants.

The components of DateTimePeriod are calculated so that adding it to this instant results in the other instant.

All components of the DateTimePeriod returned are:

  • Positive or zero if this instant is earlier than the other.

  • Negative or zero if this instant is later than the other.

  • Exactly zero if this instant is equal to the other.

Throws

if this or other instant is too large to fit in LocalDateTime. Or (only on the JVM) if the number of months between the two dates exceeds an Int.

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 period that it would take to get from the starting instant to the ending instant
val startInstant = Instant.parse("2024-01-01T02:00:00Z")
val endInstant = Instant.parse("2024-03-01T03:15:03Z")
// In New York, we find the difference between 2023-12-31 and 2024-02-29, which is just short of two months
val periodInNewYork = startInstant.periodUntil(endInstant, TimeZone.of("America/New_York"))
check(periodInNewYork == DateTimePeriod(months = 1, days = 29, hours = 1, minutes = 15, seconds = 3))
// In Berlin, we find the difference between 2024-01-01 and 2024-03-01, which is exactly two months
val periodInBerlin = startInstant.periodUntil(endInstant, TimeZone.of("Europe/Berlin"))
check(periodInBerlin == DateTimePeriod(months = 2, days = 0, hours = 1, minutes = 15, seconds = 3)) 
   //sampleEnd
}

Returns a DatePeriod representing the difference between this and other dates.

The components of DatePeriod are calculated so that adding it to this date results in the other date.

All components of the DatePeriod returned are:

  • Positive or zero if this date is earlier than the other.

  • Negative or zero if this date is later than the other.

  • Exactly zero if this date is equal to the other.

See also

for the same operation with the order of arguments reversed.

Throws

if the number of months between the two dates exceeds an Int (JVM only).

Samples

import kotlinx.datetime.*
import kotlinx.datetime.format.*
import kotlin.random.*
import kotlin.test.*
fun main() { 
   //sampleStart 
   // Finding the period between two dates
val startDate = LocalDate(2023, Month.JANUARY, 2)
val endDate = LocalDate(2024, Month.APRIL, 1)
val period = startDate.periodUntil(endDate)
check(period == DatePeriod(years = 1, months = 2, days = 30)) 
   //sampleEnd
}