Skip to content

Add conversion of Instant to/from Unix epoch second + nanosecond #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jun 11, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions core/commonMain/src/Instant.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ import kotlin.time.Duration
@OptIn(kotlin.time.ExperimentalTime::class)
public expect class Instant : Comparable<Instant> {

// TODO: primary value properties
public val epochSeconds: Long
public val nanosecondsOfSecond: Int

public fun toUnixMillis(): Long
public fun toEpochMilliseconds(): Long

public operator fun plus(duration: Duration): Instant
public operator fun minus(duration: Duration): Instant
Expand All @@ -25,7 +26,8 @@ public expect class Instant : Comparable<Instant> {

companion object {
fun now(): Instant
fun fromUnixMillis(millis: Long): Instant
fun fromEpochMilliseconds(epochMilliseconds: Long): Instant
fun fromEpochSeconds(epochSeconds: Long, nanosecondAdjustment: Long = 0): Instant
fun parse(isoString: String): Instant
}
}
Expand Down
47 changes: 35 additions & 12 deletions core/commonTest/src/InstantTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,29 +14,29 @@ class InstantTest {
@Test
fun testNow() {
val instant = Instant.now()
val millis = instant.toUnixMillis()
val millis = instant.toEpochMilliseconds()

assertTrue(millis > 1_500_000_000_000L)

println(instant)
println(instant.toUnixMillis())
println(instant.toEpochMilliseconds())

val millisInstant = Instant.fromUnixMillis(millis)
val millisInstant = Instant.fromEpochMilliseconds(millis)

assertEquals(millis, millisInstant.toUnixMillis())
assertEquals(millis, millisInstant.toEpochMilliseconds())

val notEqualInstant = Instant.fromUnixMillis(millis + 1)
val notEqualInstant = Instant.fromEpochMilliseconds(millis + 1)
assertNotEquals(notEqualInstant, instant)
}

@OptIn(ExperimentalTime::class)
@Test
fun instantArithmetic() {
val instant = Instant.now().toUnixMillis().let { Instant.fromUnixMillis(it) } // round to millis
val instant = Instant.now().toEpochMilliseconds().let { Instant.fromEpochMilliseconds(it) } // round to millis
val diffMillis = Random.nextLong(1000, 1_000_000_000)
val diff = diffMillis.milliseconds

val nextInstant = (instant.toUnixMillis() + diffMillis).let { Instant.fromUnixMillis(it) }
val nextInstant = (instant.toEpochMilliseconds() + diffMillis).let { Instant.fromEpochMilliseconds(it) }

assertEquals(diff, nextInstant - instant)
assertEquals(nextInstant, instant + diff)
Expand Down Expand Up @@ -75,7 +75,7 @@ class InstantTest {
instants.forEach {
val (str, seconds, nanos) = it
val instant = Instant.parse(str)
assertEquals(seconds.toLong() * 1000 + nanos / 1000000, instant.toUnixMillis())
assertEquals(seconds.toLong() * 1000 + nanos / 1000000, instant.toEpochMilliseconds())
}
}

Expand Down Expand Up @@ -141,8 +141,8 @@ class InstantTest {
repeat(1000) {
val millis1 = Random.nextLong(2_000_000_000_000L)
val millis2 = Random.nextLong(2_000_000_000_000L)
val instant1 = Instant.fromUnixMillis(millis1)
val instant2 = Instant.fromUnixMillis(millis2)
val instant1 = Instant.fromEpochMilliseconds(millis1)
val instant2 = Instant.fromEpochMilliseconds(millis2)

val diff = instant1.periodUntil(instant2, TimeZone.SYSTEM)
val instant3 = instant1.plus(diff, TimeZone.SYSTEM)
Expand All @@ -158,8 +158,8 @@ class InstantTest {
val millis1 = Random.nextLong(2_000_000_000_000L)
val millis2 = Random.nextLong(2_000_000_000_000L)
with(TimeZone.UTC) TZ@ {
val date1 = Instant.fromUnixMillis(millis1).toLocalDateTime().date
val date2 = Instant.fromUnixMillis(millis2).toLocalDateTime().date
val date1 = Instant.fromEpochMilliseconds(millis1).toLocalDateTime().date
val date2 = Instant.fromEpochMilliseconds(millis2).toLocalDateTime().date
fun LocalDate.instantAtStartOfDay() = LocalDateTime(year, monthNumber, dayOfMonth, 0, 0, 0, 0).toInstant()
val instant1 = date1.instantAtStartOfDay()
val instant2 = date2.instantAtStartOfDay()
Expand Down Expand Up @@ -187,6 +187,29 @@ class InstantTest {
}
}

/* Based on the ThreeTenBp project.
* Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
*/
@Test
fun nanosecondAdjustment() {
for (i in -2..2L) {
for (j in 0..9L) {
val t: Instant = Instant.fromEpochSeconds(i, j)
assertEquals(i, t.epochSeconds)
assertEquals(j, t.nanosecondsOfSecond.toLong())
}
for (j in -10..-1L) {
val t: Instant = Instant.fromEpochSeconds(i, j)
assertEquals(i - 1, t.epochSeconds)
assertEquals(j + 1000000000, t.nanosecondsOfSecond.toLong())
}
for (j in 999_999_990..999_999_999L) {
val t: Instant = Instant.fromEpochSeconds(i, j)
assertEquals(i, t.epochSeconds)
assertEquals(j, t.nanosecondsOfSecond.toLong())
}
}
}

/* Based on the ThreeTenBp project.
* Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos
Expand Down
14 changes: 10 additions & 4 deletions core/jsMain/src/Instant.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@ import kotlinx.datetime.internal.JSJoda.ZoneId
@OptIn(kotlin.time.ExperimentalTime::class)
public actual class Instant internal constructor(internal val value: jtInstant) : Comparable<Instant> {

public actual fun toUnixMillis(): Long = value.toEpochMilli().toLong()
actual val epochSeconds: Long
get() = value.epochSecond().toLong()
actual val nanosecondsOfSecond: Int
get() = value.nano().toInt()

public actual fun toEpochMilliseconds(): Long = value.toEpochMilli().toLong()

actual operator fun plus(duration: Duration): Instant = duration.toComponents { seconds, nanoseconds ->
Instant(value.plusSeconds(seconds).plusNanos(nanoseconds.toLong()))
Expand All @@ -46,13 +50,15 @@ public actual class Instant internal constructor(internal val value: jtInstant)
actual fun now(): Instant =
Instant(jtClock.systemUTC().instant())

actual fun fromUnixMillis(millis: Long): Instant =
Instant(jtInstant.ofEpochMilli(millis.toDouble()))
actual fun fromEpochMilliseconds(epochMilliseconds: Long): Instant =
Instant(jtInstant.ofEpochMilli(epochMilliseconds.toDouble()))

actual fun parse(isoString: String): Instant =
Instant(jtInstant.parse(isoString))
}

actual fun fromEpochSeconds(epochSeconds: Long, nanosecondAdjustment: Long): Instant =
Instant(jtInstant.ofEpochSecond(epochSeconds, nanosecondAdjustment))
}
}


Expand Down
14 changes: 10 additions & 4 deletions core/jvmMain/src/Instant.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,12 @@ import java.time.Clock as jtClock
@OptIn(kotlin.time.ExperimentalTime::class)
public actual class Instant internal constructor(internal val value: jtInstant) : Comparable<Instant> {

public actual fun toUnixMillis(): Long = value.toEpochMilli()
actual val epochSeconds: Long
get() = value.epochSecond
actual val nanosecondsOfSecond: Int
get() = value.nano

public actual fun toEpochMilliseconds(): Long = value.toEpochMilli()

actual operator fun plus(duration: Duration): Instant = duration.toComponents { seconds, nanoseconds ->
Instant(value.plusSeconds(seconds).plusNanos(nanoseconds.toLong()))
Expand All @@ -41,13 +45,15 @@ public actual class Instant internal constructor(internal val value: jtInstant)
actual fun now(): Instant =
Instant(jtClock.systemUTC().instant())

actual fun fromUnixMillis(millis: Long): Instant =
Instant(jtInstant.ofEpochMilli(millis))
actual fun fromEpochMilliseconds(epochMilliseconds: Long): Instant =
Instant(jtInstant.ofEpochMilli(epochMilliseconds))

actual fun parse(isoString: String): Instant =
Instant(jtInstant.parse(isoString))
}

actual fun fromEpochSeconds(epochSeconds: Long, nanosecondAdjustment: Long): Instant =
Instant(jtInstant.ofEpochSecond(epochSeconds, nanosecondAdjustment))
}
}

public actual fun Instant.plus(period: CalendarPeriod, zone: TimeZone): Instant {
Expand Down
40 changes: 24 additions & 16 deletions core/nativeMain/src/Instant.kt
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,17 @@ private val instantParser: Parser<Instant>
}

@OptIn(ExperimentalTime::class)
public actual class Instant internal constructor(internal val epochSeconds: Long, internal val nanos: Int) : Comparable<Instant> {
public actual class Instant internal constructor(actual val epochSeconds: Long, actual val nanosecondsOfSecond: Int) : Comparable<Instant> {

actual fun toUnixMillis(): Long = epochSeconds * MILLIS_PER_ONE + nanos / NANOS_PER_MILLI
// org.threeten.bp.Instant#toEpochMilli
actual fun toEpochMilliseconds(): Long =
if (epochSeconds >= 0) {
val millis: Long = safeMultiply(epochSeconds, MILLIS_PER_ONE.toLong())
safeAdd(millis, nanosecondsOfSecond / NANOS_PER_MILLI.toLong())
} else {
val millis: Long = safeMultiply(epochSeconds + 1, MILLIS_PER_ONE.toLong())
safeSubtract(millis, MILLIS_PER_ONE.toLong() - nanosecondsOfSecond / NANOS_PER_MILLI)
}

// org.threeten.bp.Instant#plus(long, long)
internal fun plus(secondsToAdd: Long, nanosToAdd: Long): Instant {
Expand All @@ -77,8 +85,8 @@ public actual class Instant internal constructor(internal val epochSeconds: Long
val epochSec: Long = safeAdd(epochSeconds, secondsToAdd)
val newEpochSeconds = safeAdd(epochSec, (nanosToAdd / NANOS_PER_ONE))
val newNanosToAdd = nanosToAdd % NANOS_PER_ONE
val nanoAdjustment = (nanos + newNanosToAdd) // safe int+NANOS_PER_ONE
return ofEpochSecond(newEpochSeconds, nanoAdjustment)
val nanoAdjustment = (nanosecondsOfSecond + newNanosToAdd) // safe int+NANOS_PER_ONE
return fromEpochSeconds(newEpochSeconds, nanoAdjustment)
}

actual operator fun plus(duration: Duration): Instant = duration.toComponents { epochSeconds, nanos ->
Expand All @@ -89,27 +97,27 @@ public actual class Instant internal constructor(internal val epochSeconds: Long

actual operator fun minus(other: Instant): Duration =
(this.epochSeconds - other.epochSeconds).seconds + // won't overflow given the instant bounds
(this.nanos - other.nanos).nanoseconds
(this.nanosecondsOfSecond - other.nanosecondsOfSecond).nanoseconds

actual override fun compareTo(other: Instant): Int {
val s = epochSeconds.compareTo(other.epochSeconds)
if (s != 0) {
return s
}
return nanos.compareTo(other.nanos)
return nanosecondsOfSecond.compareTo(other.nanosecondsOfSecond)
}

override fun equals(other: Any?): Boolean =
this === other || other is Instant && this.epochSeconds == other.epochSeconds && this.nanos == other.nanos
this === other || other is Instant && this.epochSeconds == other.epochSeconds && this.nanosecondsOfSecond == other.nanosecondsOfSecond

// org.threeten.bp.Instant#hashCode
override fun hashCode(): Int =
(epochSeconds xor (epochSeconds ushr 32)).toInt() + 51 * nanos
(epochSeconds xor (epochSeconds ushr 32)).toInt() + 51 * nanosecondsOfSecond

// org.threeten.bp.format.DateTimeFormatterBuilder.InstantPrinterParser#print
override fun toString(): String {
val buf = StringBuilder()
val inNano: Int = nanos
val inNano: Int = nanosecondsOfSecond
if (epochSeconds >= -SECONDS_0000_TO_1970) { // current era
val zeroSecs: Long = epochSeconds - SECONDS_PER_10000_YEARS + SECONDS_0000_TO_1970
val hi: Long = floorDiv(zeroSecs, SECONDS_PER_10000_YEARS) + 1
Expand Down Expand Up @@ -176,20 +184,20 @@ public actual class Instant internal constructor(internal val epochSeconds: Long
assertEquals(0, error)
// according to https://en.cppreference.com/w/c/chrono/timespec,
// tv_nsec in [0; 10^9), so no need to call [ofEpochSecond].
val seconds = timespecBuf.tv_sec.toLong() // conversion is needed on some platforms
val seconds = timespecBuf.tv_sec.convert<Long>()
val nanosec = timespecBuf.tv_nsec.toInt()
Instant(seconds, nanosec)
}

// org.threeten.bp.Instant#ofEpochMilli
actual fun fromUnixMillis(millis: Long): Instant =
Instant(floorDiv(millis, MILLIS_PER_ONE.toLong()),
(floorMod(millis, MILLIS_PER_ONE.toLong()) * NANOS_PER_MILLI).toInt())
actual fun fromEpochMilliseconds(epochMilliseconds: Long): Instant =
Instant(floorDiv(epochMilliseconds, MILLIS_PER_ONE.toLong()),
(floorMod(epochMilliseconds, MILLIS_PER_ONE.toLong()) * NANOS_PER_MILLI).toInt())

// org.threeten.bp.Instant#ofEpochSecond(long, long)
internal fun ofEpochSecond(epochSecond: Long, nanoAdjustment: Long = 0): Instant {
val secs = safeAdd(epochSecond, floorDiv(nanoAdjustment, NANOS_PER_ONE.toLong()))
val nos = floorMod(nanoAdjustment, NANOS_PER_ONE.toLong()).toInt()
actual fun fromEpochSeconds(epochSeconds: Long, nanosecondAdjustment: Long): Instant {
val secs = safeAdd(epochSeconds, floorDiv(nanosecondAdjustment, NANOS_PER_ONE.toLong()))
val nos = floorMod(nanosecondAdjustment, NANOS_PER_ONE.toLong()).toInt()
return Instant(secs, nos)
}

Expand Down
17 changes: 17 additions & 0 deletions core/nativeMain/src/Util.kt
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,23 @@ internal fun safeAdd(a: Long, b: Long): Long {
}


/**
* Safely subtracts one long from another.
*
* @param a the first value
* @param b the second value to subtract from the first
* @return the result
* @throws ArithmeticException if the result overflows a long
*/
internal fun safeSubtract(a: Long, b: Long): Long {
val result = a - b
// check for a change of sign in the result when the inputs have the different signs
if (a xor result < 0 && a xor b < 0) {
throw ArithmeticException("Subtraction overflows a long: $a - $b")
}
return result
}

/**
* Safely multiply a long by an int.
*
Expand Down
2 changes: 1 addition & 1 deletion core/nativeMain/src/ZonedDateTime.kt
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ internal fun Instant.toZonedLocalDateTime(zone: TimeZone): ZonedDateTime {
val localEpochDay: Long = floorDiv(localSecond, SECONDS_PER_DAY.toLong())
val secsOfDay: Long = floorMod(localSecond, SECONDS_PER_DAY.toLong())
val date: LocalDate = LocalDate.ofEpochDay(localEpochDay)
val time: LocalTime = LocalTime.ofSecondOfDay(secsOfDay, nanos)
val time: LocalTime = LocalTime.ofSecondOfDay(secsOfDay, nanosecondsOfSecond)
return ZonedDateTime(LocalDateTime(date, time), zone, currentOffset)
}

Expand Down
64 changes: 32 additions & 32 deletions core/nativeTest/src/ThreeTenBpInstantTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,19 @@ class ThreeTenBpInstantTest {
@Test
fun instantComparisons() {
val instants = arrayOf(
Instant.ofEpochSecond(-2L, 0),
Instant.ofEpochSecond(-2L, 999999998),
Instant.ofEpochSecond(-2L, 999999999),
Instant.ofEpochSecond(-1L, 0),
Instant.ofEpochSecond(-1L, 1),
Instant.ofEpochSecond(-1L, 999999998),
Instant.ofEpochSecond(-1L, 999999999),
Instant.ofEpochSecond(0L, 0),
Instant.ofEpochSecond(0L, 1),
Instant.ofEpochSecond(0L, 2),
Instant.ofEpochSecond(0L, 999999999),
Instant.ofEpochSecond(1L, 0),
Instant.ofEpochSecond(2L, 0)
Instant.fromEpochSeconds(-2L, 0),
Instant.fromEpochSeconds(-2L, 999999998),
Instant.fromEpochSeconds(-2L, 999999999),
Instant.fromEpochSeconds(-1L, 0),
Instant.fromEpochSeconds(-1L, 1),
Instant.fromEpochSeconds(-1L, 999999998),
Instant.fromEpochSeconds(-1L, 999999999),
Instant.fromEpochSeconds(0L, 0),
Instant.fromEpochSeconds(0L, 1),
Instant.fromEpochSeconds(0L, 2),
Instant.fromEpochSeconds(0L, 999999999),
Instant.fromEpochSeconds(1L, 0),
Instant.fromEpochSeconds(2L, 0)
)
for (i in instants.indices) {
val a = instants[i]
Expand All @@ -50,10 +50,10 @@ class ThreeTenBpInstantTest {

@Test
fun instantEquals() {
val test5a: Instant = Instant.ofEpochSecond(5L, 20)
val test5b: Instant = Instant.ofEpochSecond(5L, 20)
val test5n: Instant = Instant.ofEpochSecond(5L, 30)
val test6: Instant = Instant.ofEpochSecond(6L, 20)
val test5a: Instant = Instant.fromEpochSeconds(5L, 20)
val test5b: Instant = Instant.fromEpochSeconds(5L, 20)
val test5n: Instant = Instant.fromEpochSeconds(5L, 30)
val test6: Instant = Instant.fromEpochSeconds(6L, 20)
assertEquals(true, test5a == test5a)
assertEquals(true, test5a == test5b)
assertEquals(false, test5a == test5n)
Expand All @@ -73,20 +73,20 @@ class ThreeTenBpInstantTest {
}

@Test
fun toUnixMillis() {
assertEquals(Instant.ofEpochSecond(1L, 1000000).toUnixMillis(), 1001L)
assertEquals(Instant.ofEpochSecond(1L, 2000000).toUnixMillis(), 1002L)
assertEquals(Instant.ofEpochSecond(1L, 567).toUnixMillis(), 1000L)
assertEquals(Instant.ofEpochSecond(Long.MAX_VALUE / 1000).toUnixMillis(), Long.MAX_VALUE / 1000 * 1000)
assertEquals(Instant.ofEpochSecond(Long.MIN_VALUE / 1000).toUnixMillis(), Long.MIN_VALUE / 1000 * 1000)
assertEquals(Instant.ofEpochSecond(0L, -1000000).toUnixMillis(), -1L)
assertEquals(Instant.ofEpochSecond(0L, 1000000).toUnixMillis(), 1)
assertEquals(Instant.ofEpochSecond(0L, 999999).toUnixMillis(), 0)
assertEquals(Instant.ofEpochSecond(0L, 1).toUnixMillis(), 0)
assertEquals(Instant.ofEpochSecond(0L, 0).toUnixMillis(), 0)
assertEquals(Instant.ofEpochSecond(0L, -1).toUnixMillis(), -1L)
assertEquals(Instant.ofEpochSecond(0L, -999999).toUnixMillis(), -1L)
assertEquals(Instant.ofEpochSecond(0L, -1000000).toUnixMillis(), -1L)
assertEquals(Instant.ofEpochSecond(0L, -1000001).toUnixMillis(), -2L)
fun toEpochMilliseconds() {
assertEquals(Instant.fromEpochSeconds(1L, 1000000).toEpochMilliseconds(), 1001L)
assertEquals(Instant.fromEpochSeconds(1L, 2000000).toEpochMilliseconds(), 1002L)
assertEquals(Instant.fromEpochSeconds(1L, 567).toEpochMilliseconds(), 1000L)
assertEquals(Instant.fromEpochSeconds(Long.MAX_VALUE / 1000).toEpochMilliseconds(), Long.MAX_VALUE / 1000 * 1000)
assertEquals(Instant.fromEpochSeconds(Long.MIN_VALUE / 1000).toEpochMilliseconds(), Long.MIN_VALUE / 1000 * 1000)
assertEquals(Instant.fromEpochSeconds(0L, -1000000).toEpochMilliseconds(), -1L)
assertEquals(Instant.fromEpochSeconds(0L, 1000000).toEpochMilliseconds(), 1)
assertEquals(Instant.fromEpochSeconds(0L, 999999).toEpochMilliseconds(), 0)
assertEquals(Instant.fromEpochSeconds(0L, 1).toEpochMilliseconds(), 0)
assertEquals(Instant.fromEpochSeconds(0L, 0).toEpochMilliseconds(), 0)
assertEquals(Instant.fromEpochSeconds(0L, -1).toEpochMilliseconds(), -1L)
assertEquals(Instant.fromEpochSeconds(0L, -999999).toEpochMilliseconds(), -1L)
assertEquals(Instant.fromEpochSeconds(0L, -1000000).toEpochMilliseconds(), -1L)
assertEquals(Instant.fromEpochSeconds(0L, -1000001).toEpochMilliseconds(), -2L)
}
}