1

I am trying to get my LocalDateTime field saved as a long so I can store it in my SQLite database. How am I able to do this?

var datetime = LocalDateTime.now()
var longdt: Long = getString(datetime).toLong()
Clarke Woogner
  • 113
  • 1
  • 1
  • 8

2 Answers2

5

You can use toEpochSecond() and ofEpochSecond() to convert to/from a long value with precision to the second.

Example (in Java)

LocalDateTime now = LocalDateTime.now();
long nowInSeconds = now.toEpochSecond(ZoneOffset.UTC);
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(nowInSeconds, 0, ZoneOffset.UTC);

System.out.println("now = " + now);
System.out.println("nowInSeconds = " + nowInSeconds);
System.out.println("dateTime = " + dateTime);

Output

now = 2020-05-12T12:12:36.984263200
nowInSeconds = 1589285556
dateTime = 2020-05-12T12:12:36

If you needed the long value with precision to the millisecond, do this:

LocalDateTime now = LocalDateTime.now();
long nowInMillis = now.toEpochSecond(ZoneOffset.UTC) * 1000
                 + now.get(ChronoField.MILLI_OF_SECOND);
LocalDateTime dateTime = LocalDateTime.ofEpochSecond(nowInMillis / 1000,
                  (int) (nowInMillis % 1000 * 1000000), ZoneOffset.UTC);

System.out.println("now = " + now);
System.out.println("nowInMillis = " + nowInMillis);
System.out.println("dateTime = " + dateTime);

Output

now = 2020-05-12T12:16:38.881510700
nowInMillis = 1589285798881
dateTime = 2020-05-12T12:16:38.881

If needed, specify a zone offset other than UTC, but in that case you should really be using ZonedDateTime or OffsetDateTime instead of LocalDateTime.

Andreas
  • 154,647
  • 11
  • 152
  • 247
2

If by long you mean number of second or millisecond use this way.

LocalDateTime in Epoch seconds

val seconds = datetime.atZone(ZoneOffset.UTC).toEpochSecond())

LocalDateTime to epoch milliseconds

val milliseconds = datetime.atZone(ZoneOffset.UTC)?.toInstant()?.toEpochMilli()
Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • The question is how to get a `long` value from a `LocalDateTime`, not the other way around shown here. – Andreas May 12 '20 at 16:00
  • 1
    @Andreas Okay, I think long means epoch second. I don't understand your point accually. – Eklavya May 12 '20 at 16:02
  • I was looking at an old version of this answer, that converted a `seconds` value into a `LocalDateTime` value. – Andreas May 12 '20 at 16:21
  • 1
    `atZone()` cannot return `null`, so why use `?.`? --- Why not use `datetime.toEpochSecond(ZoneOffset.UTC)`? --- Why not use `datetime.toInstant(ZoneOffset.UTC).toEpochMilli()`? – Andreas May 12 '20 at 16:23
  • @Andreas Maybe I miss something, I didn't find `toInstant()` in this document https://developer.android.com/reference/kotlin/java/time/LocalDateTime – Eklavya May 12 '20 at 16:59
  • 1
    Expand "From class `ChronoLocalDateTime`" (below the method list). It's a `default` method from that interface. – Andreas May 12 '20 at 18:17