【发布时间】:2019-02-28 14:27:42
【问题描述】:
我需要能够使用 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);
}
}}
【问题讨论】:
-
LocalDateTime是用于此目的的错误类。缺少任何时区或与 UTC 偏移的概念意味着此类不能代表一个时刻。跟踪时刻(例如自 1970-01-01T00:00:00Z 以来的毫秒数)时,请使用Instant或OffsetDateTime或ZonedDateTime类。这三个类do 代表一个时刻,而LocalDateTime代表not。Instant.ofEpochMilli( milliseconds ) -
@BasilBourque 你会推荐什么作为转到 DateTime(将在 c# 中)参数类型?
-
正如我在评论末尾的代码中所示,
Instant是 java.time 的基本构建块类。根据定义,Instant始终采用 UTC。对于其他偏移量,请使用OffsetDateTime。对于完整时区而不是单纯的偏移,请使用ZonedDateTime。仅限日期,LocalDate。这已经在 Stack Overflow 上讨论过很多次了,所以请搜索更多信息。您可以从昨天的my Answer 开始。然后使用 DuckDuckGo/Google/Bing 中的site:stackoverflow.com技巧在 Stack Overflow 中搜索类名。
标签: java android android-room