Skip to content

Commit

Permalink
Updated logic to properly convert zoned date time (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
oleksandrsarapulovgl authored Jul 21, 2021
1 parent 5ef86a8 commit 22f1864
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
10 changes: 10 additions & 0 deletions .idea/sonarIssues.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import dgca.verifier.app.engine.UTC_ZONE_ID
import java.time.Instant
import java.time.LocalDate
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit


/*-
Expand Down Expand Up @@ -70,16 +71,19 @@ class Converters {

@TypeConverter
fun fromTimestamp(value: Long?): ZonedDateTime = if (value != null) {
val instant: Instant = Instant.ofEpochMilli(value)
val instant: Instant = Instant.EPOCH.plus(value, ChronoUnit.MICROS)
ZonedDateTime.ofInstant(instant, UTC_ZONE_ID)
} else {
ZonedDateTime.now(UTC_ZONE_ID)
}

@TypeConverter
fun zonedDateTimeToTimestamp(zonedDateTime: ZonedDateTime?): Long {
return (zonedDateTime?.withZoneSameInstant(UTC_ZONE_ID)
?: ZonedDateTime.now(UTC_ZONE_ID)).toInstant().toEpochMilli()
return ChronoUnit.MICROS.between(
Instant.EPOCH,
(zonedDateTime?.withZoneSameInstant(UTC_ZONE_ID)
?: ZonedDateTime.now(UTC_ZONE_ID)).toInstant()
)
}

@TypeConverter
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,19 @@ internal class ConvertersTest {
)
}

@Test
fun testConverterEdgeCase() {
val converters = Converters()
val zonedDateTimeZone = ZonedDateTime.parse("2021-06-30T14:54:51.748565Z")
val timestamp = converters.zonedDateTimeToTimestamp(zonedDateTimeZone)
val actualZonedDateTime = converters.fromTimestamp(timestamp)

assertEquals(
zonedDateTimeZone.withZoneSameInstant(utcZoneId),
actualZonedDateTime
)
}

@Test
fun testListOfStringConverter() {
val expected = listOf("one", "two", "three")
Expand Down

0 comments on commit 22f1864

Please sign in to comment.