What is the best practice for preserving regional time zone offsets in Realm Java/Kotlin?
0 reputation · 23 Jun 2026, 08:04 UTC
0 reputation · 23 Jun 2026, 08:04 UTC
Realm stores date objects as 64-bit integers representing milliseconds since the Unix epoch (UTC). Because the SDK treats dates as absolute points in time, it does not natively store time zone metadata within the date field itself.
When an application needs to reconstruct a specific regional time or handle daylight savings transitions, the conversion must be managed at the application layer using libraries such as java.time. However, storing dates as strings to preserve this metadata bypasses Realm's optimized date indexing and query operators.
There is a design tension between maintaining query performance via the native Date type and the requirement to store precise regional offsets for accurate local time reconstruction.
Which architectural approach is recommended for storing time zone offsets without sacrificing indexing efficiency? Does storing a separate integer offset field alongside the UTC date provide sufficient precision for all regional transitions?
35275 reputation · 23 Jun 2026, 16:14 UTC
Use a dual‑field approach: store the event time as a native java.util.Date (UTC) and keep a separate String that holds the IANA ZoneId (e.g., America/New_York). This preserves query performance while enabling accurate local‑time reconstruction.
Date type is indexed and supports range queries, sorting, and other date operators.ZonedDateTime can compute the correct offset for any instant.open class Event : RealmObject() {
var timestamp: Date? = null // UTC instant
var zoneId: String? = null // IANA zone ID
}
ZonedDateTime to UTC before storing:
val now = ZonedDateTime.now(ZoneId.of("America/New_York"))
val event = realm.createObject(Event::class.java)
event.timestamp = Date.from(now.toInstant())
event.zoneId = now.zone.id
val instant = event.timestamp.toInstant()
val zone = ZoneId.of(event.zoneId)
val local = ZonedDateTime.ofInstant(instant, zone)
timestamp for range, sorting, etc., without touching zoneId.
Does your application need to handle future changes to regional time‑zone rules (e.g., a country adopting a new DST policy)? If so, the IANA ZoneId approach is mandatory; an integer offset would become invalid over time.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.