Timestamps - Kotlin SDK
You cannot store Kotlin's built-in Date
or Instant
types in Realm
Database. Instead, use the
RealmInstant
type, which stores time information as a UNIX epoch timestamp.
If you need timestamp data in a form other than RealmInstant
, you
can add conversion code to your model class based on the following
example:
// model class that stores an Instant (kotlinx-datetime) field as a RealmInstant via a conversion class RealmInstantConversion : RealmObject { private var _timestamp: RealmInstant = RealmInstant.from(0, 0) public var timestamp: Instant get() { return _timestamp.toInstant() } set(value) { _timestamp = value.toRealmInstant() } } fun RealmInstant.toInstant(): Instant { val sec: Long = this.epochSeconds // The value always lies in the range `-999_999_999..999_999_999`. // minus for timestamps before epoch, positive for after val nano: Int = this.nanosecondsOfSecond return if (sec >= 0) { // For positive timestamps, conversion can happen directly Instant.fromEpochSeconds(sec, nano.toLong()) } else { // For negative timestamps, RealmInstant starts from the higher value with negative // nanoseconds, while Instant starts from the lower value with positive nanoseconds // TODO This probably breaks at edge cases like MIN/MAX Instant.fromEpochSeconds(sec - 1, 1_000_000 + nano.toLong()) } } fun Instant.toRealmInstant(): RealmInstant { val sec: Long = this.epochSeconds // The value is always positive and lies in the range `0..999_999_999`. val nano: Int = this.nanosecondsOfSecond return if (sec >= 0) { // For positive timestamps, conversion can happen directly RealmInstant.from(sec, nano) } else { // For negative timestamps, RealmInstant starts from the higher value with negative // nanoseconds, while Instant starts from the lower value with positive nanoseconds // TODO This probably breaks at edge cases like MIN/MAX RealmInstant.from(sec + 1, -1_000_000 + nano) } }