bod*_*vix 5 java android android-room
我需要能够使用 Room 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);
}
}}
Run Code Online (Sandbox Code Playgroud)
我已经LocalDateTimeConverter在我的库中实现了一个,手提箱,这里。请记住,这个扩展我的BaseConverter班在这里。注意:这一切都在 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
您上面使用的代码不起作用的原因是因为在您的toTimestamp()函数中,您只是要求将一天中的小时作为Long. 因此,假设LocalDateTime是 2019 年 1 月 1 日下午 12:00,您正在存储12. 因此,在 中toDate,您要求将时间戳转换12为 a LocalDateTime,即 1970 年 1 月 1 日午夜之后的 12 毫秒。
您可以选择继续使用时间戳来存储您的日期,只需将该行更改toTimestamp()为date.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(). 这将为您提供LocalDateTime当前时区的实际时间戳。请注意此处的时区:当您使用系统的默认时区来保存/加载到/从数据库中时,如果系统更改时区,您可能会得到错误的值。如果我在纽约使用您的应用程序,然后在旧金山重新打开该应用程序,则所有时间都会关闭 3 小时。最好使用设置的时区来保存/加载,然后将其转换为设备的当前时区。