https://kotlinlang.org logo
#kotlinx-datetime
Title
# kotlinx-datetime
c

Colton Idle

03/06/2023, 2:38 PM
What's the preferred way to see if a kotlin instant is greater than 7 days away?
k

kevin.cianfarini

03/06/2023, 2:43 PM
Copy code
/**
 * Check if [this] is more than 7 days in the future compared to [from].
 */ 
fun Instant.isMoreThanSevenDaysAway(from: Instant, timeZone: TimeZone): Boolean {
  val sevenDaysFrom = from.plus(value = 7, dateTimeUnit = DateTimeUnit.DAY, timeZone = timeZone)
  return this > sevenDaysFrom
}
I think this would get you what you need?
c

Colton Idle

03/06/2023, 2:45 PM
alright so just using > is enough to compare. I was intially doing ~
kotlinInstant.toJavaInstant.isBefore(kotlinInstant.toJavaInstant.add(Durations.days(7)
k

kevin.cianfarini

03/06/2023, 2:47 PM
>
just uses
compareTo
. It should be fine
c

CLOVIS

03/06/2023, 4:58 PM
7 days away can mean two things: • in 24*7 hours • at midnight on the 7th day (between 24*6 and 24*7 hours, depending on timezones and the current date) The first is just
yourInstant > clock.now() + 7.days
I don't know from memory how to do the other one, but keep in mind which one you want
k

kevin.cianfarini

03/06/2023, 5:02 PM
Int.days
is always assumed to be 24 hours which fails to consider daylight savings time.
Copy code
/**
     * Time unit representing one day, which is always equal to 24 hours.
     */
    DAYS;
To properly make this comparison the addition must be sensitive to timezones (and therefore daylight savings time). kotlinx.datetime handles this with
DateTimeUnit.DAY
which is not time based, it’s a day based metric where a day can be 23, 24, or 25 hours.
See the docs for
DayBased
in kotlinx for rationale.
Copy code
/**
     * A date-time unit equal to some number of calendar days.
     *
     * A calendar day is not considered identical to 24 hours, thus a `DayBased`-unit cannot be expressed as a multiple of some [TimeBased]-unit.
     *
     * The reason lies in time zone transitions, because of which some days can be 23 or 25 hours.
     * For example, we say that exactly a whole day has passed between `2019-10-27T02:59` and `2019-10-28T02:59`
     * in Berlin, despite the fact that the clocks were turned back one hour, so there are, in fact, 25 hours
     * between the two date-times.
     */
    @Serializable(with = DayBasedDateTimeUnitSerializer::class)
    public class DayBased(
i

ilya.gorbunov

03/08/2023, 2:30 PM
now.daysUntil(instant, timeZone) >= 7
220 Views