Skip to content

Commit ff32ad0

Browse files
authored
kotlinx.datetime.Instant conversions to and from JS Date (#171)
1 parent 91f734a commit ff32ad0

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

core/js/src/Converters.kt

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
* Copyright 2019-2021 JetBrains s.r.o.
3+
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
4+
*/
5+
6+
package kotlinx.datetime
7+
8+
import kotlin.js.*
9+
10+
/**
11+
* Converts the [Instant] to an instance of JS [Date].
12+
*
13+
* The conversion is lossy: JS uses millisecond precision to represent dates, and [Instant] allows for nanosecond
14+
* resolution.
15+
*/
16+
public fun Instant.toJSDate(): Date = Date(milliseconds = toEpochMilliseconds().toDouble())
17+
18+
/**
19+
* Converts the JS [Date] to the corresponding [Instant].
20+
*/
21+
public fun Date.toKotlinInstant(): Instant = Instant.fromEpochMilliseconds(getTime().toLong())

core/js/test/JsConverterTest.kt

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* Copyright 2019-2021 JetBrains s.r.o.
3+
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
4+
*/
5+
6+
package kotlinx.datetime.test
7+
8+
import kotlinx.datetime.*
9+
import kotlin.js.*
10+
import kotlin.test.*
11+
12+
class JsConverterTest {
13+
@Test
14+
fun toJSDateTest() {
15+
val releaseInstant = "2016-02-15T00:00Z".toInstant()
16+
val releaseDate = releaseInstant.toJSDate()
17+
assertEquals(2016, releaseDate.getUTCFullYear())
18+
assertEquals(1, releaseDate.getUTCMonth())
19+
assertEquals(15, releaseDate.getUTCDate())
20+
}
21+
22+
@Test
23+
fun toInstantTest() {
24+
val kotlinReleaseEpochMilliseconds = 1455494400000
25+
val releaseDate = Date(milliseconds = kotlinReleaseEpochMilliseconds)
26+
val releaseInstant = "2016-02-15T00:00Z".toInstant()
27+
assertEquals(releaseInstant, releaseDate.toKotlinInstant())
28+
}
29+
}

0 commit comments

Comments
 (0)