monthsUntil

fun Instant.monthsUntil(other: Instant, timeZone: TimeZone): Int(source)

Returns the number of whole months between two instants in the specified timeZone.

If the result does not fit in Int, returns Int.MAX_VALUE for a positive result or Int.MIN_VALUE for a negative result.

See also

Throws

if this or other instant is too large to fit in LocalDateTime.

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 number of months between two instants in the given time zone
val startInstant = Instant.parse("2024-01-01T02:00:00Z")
val endInstant = Instant.parse("2024-03-01T02:00:00Z")
// In New York, we find the difference between 2023-12-31 and 2024-02-29, which is just short of two months
val monthsBetweenInNewYork = startInstant.monthsUntil(endInstant, TimeZone.of("America/New_York"))
check(monthsBetweenInNewYork == 1)
// In Berlin, we find the difference between 2024-01-01 and 2024-03-01, which is exactly two months
val monthsBetweenInBerlin = startInstant.monthsUntil(endInstant, TimeZone.of("Europe/Berlin"))
check(monthsBetweenInBerlin == 2) 
   //sampleEnd
}

Returns the number of whole months between two dates.

The value is rounded toward zero.

If the result does not fit in Int, returns Int.MAX_VALUE for a positive result or Int.MIN_VALUE for a negative result.

See also

Samples

import kotlinx.datetime.*
import kotlinx.datetime.format.*
import kotlin.random.*
import kotlin.test.*

fun main() { 
   //sampleStart 
   // Finding how many months have passed between two dates
val babyDateOfBirth = LocalDate(2023, Month.DECEMBER, 14)
val today = LocalDate(2024, Month.APRIL, 16)
val ageInMonths = babyDateOfBirth.monthsUntil(today)
check(ageInMonths == 4) 
   //sampleEnd
}