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()
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()
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.
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()