我需要能够使用 Rooms TypeConverters 在我的 sqlite 数据库上存储和检索 LocalDateTime 属性。
经过一番研究,我实现了以下转换器。但是,此转换器似乎仅存储默认日期时间 (1970-01-01)。那么转换不正确有人有可用的 LocalDateTime 转换器吗?或者对此有什么改进吗?
public class LocalDateTimeConverter {
@TypeConverter
public static LocalDateTime toDate(Long timestamp) {
LocalDateTime ldt;
if (timestamp == null){
return null;
}else{
ldt = Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).toLocalDateTime();
}
return ldt;
}
@TypeConverter
public static Long toTimestamp(LocalDateTime date) {
if (date == null){
return null;
}else {
return date.getLong(ChronoField.CLOCK_HOUR_OF_DAY);
}
}}
最佳答案
我已经实现了 LocalDateTimeConverter
在我的图书馆,手提箱,here 。请记住,这扩展了我的 BaseConverter
类here 。注意:这一切都在 Kotlin 中。
如果您想自己实现,我建议存储为字符串而不是时间戳。如果您查看上面的链接,您会发现我首先使用 toString()
将日期转换为字符串。 ,然后返回 LocalDateTime
使用parse()
功能。
这是 Java 版本:
public class LocalDateTimeConverter {
@TypeConverter
public static LocalDateTime toDate(String dateString) {
if (dateString == null) {
return null;
} else {
return LocalDateTime.parse(dateString);
}
}
@TypeConverter
public static String toDateString(LocalDateTime date) {
if (date == null) {
return null;
} else {
return date.toString();
}
}
}
编辑:
您上面使用的代码不起作用的原因是在您的 toTimestamp()
中函数,您只需将一天中的时间作为 Long
来询问。所以给定一个LocalDateTime
即2019年1月1日中午12点,您正在存储12
。所以在 toDate
,您要求转换时间戳 12
到 LocalDateTime
,即 1970 年 1 月 1 日午夜过后 12 毫秒。
您可以选择继续使用时间戳来存储日期,只需更改 toTimestamp()
中的该行即可。至date.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()
。这将为您提供 LocalDateTime
的实际时间戳。在当前时区。请注意此处的时区:当您使用系统的默认时区保存数据库或从数据库加载时,如果系统更改时区,您可能会得到错误的值。如果我在纽约使用您的应用程序,然后在旧金山重新打开该应用程序,所有时间都会缩短 3 小时。最好使用设置的时区来保存/加载,然后将其转换为设备的当前时区。
关于java - 房间本地日期时间类型转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54927913/