/kotlin-duration-extensions

A set of extension properties on Int, Long, Double, and Duration, that makes it easier to work with Kotlin Duration

Primary LanguageKotlinMIT LicenseMIT

Kotlin Duration Extensions

Download

Gradle

Groovy

repositories {
  mavenCentral()
}

implementation 'com.eygraber:kotlin-duration-extensions:1.0.0'

Kotlin

repositories {
  mavenCentral()
}

implementation("com.eygraber:kotlin-duration-extensions:1.0.0")

Snapshots

Snapshots can be found at the Sonatype s01 repository:

Groovy

repositories {
  maven { url 'https://s01.oss.sonatype.org/content/repositories/snapshots' }
}

Kotlin

repositories {
  maven(url = "https://s01.oss.sonatype.org/content/repositories/snapshots")
}

Usage

Extension properties are supplied on Int, Long, and Double to make creating a Duration simpler:

2.nanoseconds
2.microseconds
2.milliseconds
2.seconds
2.minutes
2.hours
2.days

There are also extension properties supplied on Duration to get the underlying value as a Double:

val duration = 2.seconds

duration.inDoubleNanoseconds
duration.inDoubleMicroseconds
duration.inDoubleMilliseconds
duration.inDoubleSeconds
duration.inDoubleMinutes
duration.inDoubleHours
duration.inDoubleDays

Rationale

The Int, Long, and Double extension properties for creating a Duration have been deprecated in Kotlin 1.5.

There's been some discussion about it on the Kotlin Slack channel and the KEEP for Duration and time measurement API, and it seems unlikely that it will come back in the stdlib.

This library brings them back 🎉

In addition, the Duration properties that returned the value as a Double have been deprecated. This is because Duration is now backed by a Long.

The new way to retrieve the value as a Double is to use Duration.toDouble(DurationUnit). That can be a little verbose, so this library provides Duration.inDouble* functions.