java - 房间本地日期时间类型转换器

标签 java android android-room

我需要能够使用 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 。请记住,这扩展了我的 BaseConverterhere 。注意:这一切都在 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 ,您要求转换时间戳 12LocalDateTime ,即 1970 年 1 月 1 日午夜过后 12 毫秒。

您可以选择继续使用时间戳来存储日期,只需更改 toTimestamp() 中的该行即可。至date.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() 。这将为您提供 LocalDateTime 的实际时间戳。在当前时区。请注意此处的时区:当您使用系统的默认时区保存数据库或从数据库加载时,如果系统更改时区,您可能会得到错误的值。如果我在纽约使用您的应用程序,然后在旧金山重新打开该应用程序,所有时间都会缩短 3 小时。最好使用设置的时区来保存/加载,然后将其转换为设备的当前时区。

关于java - 房间本地日期时间类型转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54927913/

相关文章:

android - 通过 Dagger 2 提供 RoomDatabase 时实现 .addCallback() 的正确方法是什么?

sql - Android Room Embedded Relation 忽略 SQL where 条件

java - 将 SWT 表数据导出到 Excel 电子表格

java - Android SQLite : get number of rows in a table?

android - ADT 需要更新但找不到更新

android - TextInputLayout 提示文本颜色在焦点上改变

java - 如何引用android文档?

java - 如何对不同的服务进行分组来执行基本逻辑?

android - 如何从动态 EditText 中获取值并将值存储在整数数组中?

android - 如何从后台服务更新 ViewModel 的 LiveData 并更新 UI