房间LocalDateTime类型转换器

时间:2019-02-28 14:27:42

标签: java android android-room

我需要能够使用Rooms TypeConverters在我的sqlite数据库上存储和检索LocalDateTime属性。

经过研究,我实现了以下转换器。但是,此转换器似乎只存储默认的日期时间(1970-01-01)。那么转换是否正确?是否有人可以使用LocalDateTime Converter?或对此有任何改进?

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);
    }
}}

1 个答案:

答案 0 :(得分:1)

我已经在我的图书馆手提箱here中实现了LocalDateTimeConverter。请记住,这扩展了我的BaseConverterhere。注意:这一切都在Kotlin中。

如果您想实现自己,我建议将其存储为String而不是时间戳。如果您查看了上面的链接,您将看到我首先使用toString()将日期转换为String,然后使用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:00,您将存储12。因此,在toDate中,您要求将时间戳12转换为LocalDateTime,即1970年1月1日午夜之后的12毫秒。

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