Skip to content

Add js.Date converter #171

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 1 commit into from
Jan 10, 2022
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
21 changes: 21 additions & 0 deletions core/js/src/Converters.kt
Original file line number Diff line number Diff line change
@@ -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())
29 changes: 29 additions & 0 deletions core/js/test/JsConverterTest.kt
Original file line number Diff line number Diff line change
@@ -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())
}
}