LocalDateTime to RealmInstant conversion?

Okay so in my application from a Date/Time picker I’m allowing a user to make a choice. That choice is later represented as a LocalDateTime type. Now I want to upload that LocalDateTime to Mongo DB Atlas/Realm. However the type that I’ve defined in the schema is a date (RealmInstant).

So my question is, how can I convert a “LocalDateTime” into a “RealmInstant” format?

Have you tried RealmInstant.from() with something like LocalDateTime.now().toInstant(ZoneOffset.UTC) to get required parameters ?

When I try that approach:

RealmInstant.from(date.toInstant(ZoneOffset.UTC).epochSecond, 0)

Then in the database I get a different date format:

A regular RealmInstant date format:
+054860-03-23T17:21:49.000+00:00

Date format when I convert LocalDateTime into RealmInstant:
2022-11-21T19:12:42.000+00:00

As you can see those two do not have the same formatted string in the database.
And when I parse the second example in my app, instead of the correct date, I’m getting a year 1970:

DateTimeFormatter.ofPattern("dd MMM yyyy").format(date)

Hello Again,

This works for me, both localDP & date return the same value, didn’t check on Atlas.

    val localDP = LocalDateTime.parse("2022-11-21T19:12:42")
    val realmDP = RealmInstant.from(localDP.toEpochSecond(ZoneOffset.UTC), localDP.nano)
    val date = LocalDateTime.ofEpochSecond(realmDP.epochSeconds, realmDP.nanosecondsOfSecond, ZoneOffset.UTC)

    Log.e("Container", "Container: $realmDP -- $date.")
1 Like

Thanks for your answer, I couldn’t figure that out myself. :slight_smile:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.