Cla*_*ner 1 java android kotlin localdatetime
我正在尝试将 LocalDateTime 字段保存为 long,以便可以将其存储在 SQLite 数据库中。我怎样才能做到这一点?
var datetime = LocalDateTime.now()
var longdt: Long = getString(datetime).toLong()
Run Code Online (Sandbox Code Playgroud)
您可以使用toEpochSecond()和与精确到秒的值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);
Run Code Online (Sandbox Code Playgroud)
输出
now = 2020-05-12T12:12:36.984263200
nowInSeconds = 1589285556
dateTime = 2020-05-12T12:12:36
Run Code Online (Sandbox Code Playgroud)
如果您需要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);
Run Code Online (Sandbox Code Playgroud)
输出
now = 2020-05-12T12:16:38.881510700
nowInMillis = 1589285798881
dateTime = 2020-05-12T12:16:38.881
Run Code Online (Sandbox Code Playgroud)
如果需要,请指定除 之外的区域偏移量UTC,但在这种情况下,您实际上应该使用ZonedDateTime或OffsetDateTime而不是LocalDateTime。