Skip to content

Implement parsing Instant with offset #107

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 6 commits into from
Apr 16, 2021
Merged
Changes from 1 commit
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
10 changes: 9 additions & 1 deletion core/jvm/src/Instant.kt
Original file line number Diff line number Diff line change
Expand Up @@ -64,11 +64,19 @@ public actual class Instant internal constructor(internal val value: jtInstant)
Instant(jtInstant.ofEpochMilli(epochMilliseconds))

public actual fun parse(isoString: String): Instant = try {
Instant(jtOffsetDateTime.parse(isoString).toInstant())
Instant(jtOffsetDateTime.parse(fixOffsetRepresentation(isoString)).toInstant())
} catch (e: DateTimeParseException) {
throw DateTimeFormatException(e)
}

/** A workaround for a quirk of the JDKs older than 11 where the string representations of Instant that have an
* offset of the form "+XX" are not recognized by [jtOffsetDateTime.parse], while "+XX:XX" work fine. */
private fun fixOffsetRepresentation(isoString: String): String {
val time = isoString.split("T").elementAtOrNull(1) ?: return isoString
val offset = time.split("+", "-").elementAtOrNull(1) ?: return isoString
return if (offset.contains(":")) isoString else "$isoString:00"
}

public actual fun fromEpochSeconds(epochSeconds: Long, nanosecondAdjustment: Long): Instant = try {
Instant(jtInstant.ofEpochSecond(epochSeconds, nanosecondAdjustment))
} catch (e: Exception) {
Expand Down