Skip to content

Commit a566d2d

Browse files
committed
Use DateTimeFormatter in date adapters
Should guarantee thread safety without constantly re-creating formatters.
1 parent f601bf6 commit a566d2d

File tree

2 files changed

+19
-19
lines changed

2 files changed

+19
-19
lines changed
Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,23 @@
11
package eu.pretix.libpretixsync.sqldelight
22

33
import app.cash.sqldelight.ColumnAdapter
4-
import java.text.SimpleDateFormat
4+
import java.time.Instant
5+
import java.time.OffsetDateTime
6+
import java.time.ZoneId
7+
import java.time.format.DateTimeFormatter
58
import java.util.Date
6-
import java.util.TimeZone
79

810
class AndroidUtilDateAdapter : ColumnAdapter<Date, String> {
11+
private val df = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXXXX")
12+
913
override fun decode(databaseValue: String): Date {
10-
try {
11-
val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").apply {
12-
timeZone = TimeZone.getTimeZone("UTC")
13-
}
14-
return df.parse(databaseValue)
15-
} catch (e: Throwable) {
16-
throw e
17-
}
14+
// Use the default formatter (ISO_OFFSET_DATE_TIME) when decoding to be on the safe side
15+
// in case we encounter valid ISO strings with a slightly different format (e.g. including
16+
// milliseconds)
17+
return Date(OffsetDateTime.parse(databaseValue).toInstant().toEpochMilli())
1818
}
1919

2020
override fun encode(value: Date): String {
21-
val df = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").apply {
22-
timeZone = TimeZone.getTimeZone("UTC")
23-
}
24-
return df.format(value)
21+
return df.format(Instant.ofEpochMilli(value.time).atZone(ZoneId.of("Z")))
2522
}
2623
}
Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,21 @@
11
package eu.pretix.libpretixsync.sqldelight
22

33
import app.cash.sqldelight.ColumnAdapter
4-
import java.text.SimpleDateFormat
4+
import java.time.Instant
5+
import java.time.LocalDateTime
6+
import java.time.ZoneId
7+
import java.time.ZoneOffset
8+
import java.time.format.DateTimeFormatter
59
import java.util.Date
610

711
class JavaUtilDateAdapter : ColumnAdapter<Date, String> {
12+
private val df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
813

914
override fun decode(databaseValue: String): Date {
10-
val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
11-
return df.parse(databaseValue)
15+
return Date(LocalDateTime.parse(databaseValue, df).toInstant(ZoneOffset.UTC).toEpochMilli())
1216
}
1317

1418
override fun encode(value: Date): String {
15-
val df = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
16-
return df.format(value)
19+
return df.format(Instant.ofEpochMilli(value.time).atZone(ZoneId.of("Z")))
1720
}
1821
}

0 commit comments

Comments
 (0)