我正在尝试将我的 LocalDateTime 字段保存为 long,以便我可以将其存储在我的 SQLite 数据库中。我怎么能做到这一点?
var datetime = LocalDateTime.now()
var longdt: Long = getString(datetime).toLong()
我正在尝试将我的 LocalDateTime 字段保存为 long,以便我可以将其存储在我的 SQLite 数据库中。我怎么能做到这一点?
var datetime = LocalDateTime.now()
var longdt: Long = getString(datetime).toLong()
您可以使用toEpochSecond()
and将一个精确到秒的值ofEpochSecond()
转换为/从一个值转换。long
示例(在 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);
输出
now = 2020-05-12T12:12:36.984263200
nowInSeconds = 1589285556
dateTime = 2020-05-12T12:12:36
如果您需要long
精确到毫秒的值,请执行以下操作:
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);
输出
now = 2020-05-12T12:16:38.881510700
nowInMillis = 1589285798881
dateTime = 2020-05-12T12:16:38.881
如果需要,请指定除 之外的区域偏移量UTC
,但在这种情况下,您应该使用ZonedDateTime
orOffsetDateTime
代替LocalDateTime
。
如果用 long 表示以这种方式使用的秒数或毫秒数。
LocalDateTime 以 Epoch 秒为单位
val seconds = datetime.atZone(ZoneOffset.UTC).toEpochSecond())
LocalDateTime 到纪元毫秒
val milliseconds = datetime.atZone(ZoneOffset.UTC)?.toInstant()?.toEpochMilli()