diff --git a/core/js/src/Converters.kt b/core/js/src/Converters.kt new file mode 100644 index 000000000..e161718a1 --- /dev/null +++ b/core/js/src/Converters.kt @@ -0,0 +1,21 @@ +/* + * Copyright 2019-2021 JetBrains s.r.o. + * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. + */ + +package kotlinx.datetime + +import kotlin.js.* + +/** + * Converts the [Instant] to an instance of JS [Date]. + * + * The conversion is lossy: JS uses millisecond precision to represent dates, and [Instant] allows for nanosecond + * resolution. + */ +public fun Instant.toJSDate(): Date = Date(milliseconds = toEpochMilliseconds().toDouble()) + +/** + * Converts the JS [Date] to the corresponding [Instant]. + */ +public fun Date.toKotlinInstant(): Instant = Instant.fromEpochMilliseconds(getTime().toLong()) diff --git a/core/js/test/JsConverterTest.kt b/core/js/test/JsConverterTest.kt new file mode 100644 index 000000000..c2f3cc3b6 --- /dev/null +++ b/core/js/test/JsConverterTest.kt @@ -0,0 +1,29 @@ +/* + * Copyright 2019-2021 JetBrains s.r.o. + * Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file. + */ + +package kotlinx.datetime.test + +import kotlinx.datetime.* +import kotlin.js.* +import kotlin.test.* + +class JsConverterTest { + @Test + fun toJSDateTest() { + val releaseInstant = "2016-02-15T00:00Z".toInstant() + val releaseDate = releaseInstant.toJSDate() + assertEquals(2016, releaseDate.getUTCFullYear()) + assertEquals(1, releaseDate.getUTCMonth()) + assertEquals(15, releaseDate.getUTCDate()) + } + + @Test + fun toInstantTest() { + val kotlinReleaseEpochMilliseconds = 1455494400000 + val releaseDate = Date(milliseconds = kotlinReleaseEpochMilliseconds) + val releaseInstant = "2016-02-15T00:00Z".toInstant() + assertEquals(releaseInstant, releaseDate.toKotlinInstant()) + } +}