我已经为此工作了几个小时,但我似乎不知道如何将日期保存到我的 Room Sqllite 数据库中。我基本上是从 Android 文档中批量复制代码来完成此操作。
这就是我所拥有的。
数据库:
@Database(entities = {Review.class},
version = 3,
exportSchema=false)
@TypeConverters(DateTypeConverter.class)
public abstract class NotecardDatabase extends RoomDatabase {
...etc...
}
实体:
@Entity(tableName = "review",
indices = {
@Index(value = "next_review"),
}
public class Review {
...Other columns...
@TypeConverters(DateTypeConverter.class)
@ColumnInfo(name ="next_review")
@NonNull
private Date nextReview;
}
接下来,我的转换器:
public class DateTypeConverter {
private static Logger log = Logger.getLogger("DateTypeConverter");
@TypeConverter
public static Date fromTimestamp(Long value) {
if(value != null) {
log.info("Incoming long: " + value + "\nTo Date: " + new Date(value));
}
return value == null ? null : new Date(value);
}
@TypeConverter
public static Long dateToTimestamp(Date date) {
if(date != null) {
log.info("Incoming date: " + date + "\n to Long: " + date.getTime());
}
return date == null ? null : date.getTime();
}
}
最后,这是当我尝试创建一些 Review 对象时运行该命令得到的输出:
06-18 18:13:38.522 7081-7098/DateTypeConverter: 传入日期: 2018 年太平洋夏令时 6 月 18 日星期一 18:13:38 长:1529370818524
06-18 18:13:38.522 7081-7106/DateTypeConverter: 传入长:1529370818 迄今为止:1970 年 1 月 18 日星期日 08:49:30 PST 1970
看起来它保存正确(参见第一个日志语句),但是当我从数据库中取出该内容时,长整型的最后 3 位数字被简单地截掉,返回 1970 年的日期。
帮忙?
最佳答案
好的,经过一番努力,我解决了这个问题。感谢所有为此提供帮助的人。
我从“日期”更改为“日历”,但这并不能解决此问题。
真正的问题是有两个时间戳:Linux 时间戳(自纪元以来的毫秒)和 Java/Sqllite 时间戳(自纪元以来的秒)。
为了让一切与 Sqllite 函数完美配合,并正确保存和读取,这是我的工作代码:
public class DateTypeConverter {
@TypeConverter
public static Calendar calendarFromTimestamp(String value) {
if(value == null) {
return null;
}
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(NumberUtils.toLong(value)*1000);
return cal;
}
@TypeConverter
public static String dateToTimestamp(Calendar cal) {
if(cal == null) {
return null;
}
return "" + cal.getTimeInMillis()/1000;
}
}
请注意 cal.getTimeInMillis() 函数的用法,该函数明确指出我们正在执行毫秒时间戳。然后在保存到数据库时,我们除以1000来保存秒时间戳,因为Sqllite日期函数处理秒时间戳。
另请注意,您也可以使用长整型而不是字符串,但字符串对我有用。
关于java - 将日期保存到 Room 数据库时,TypeConverter 会扰乱数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50919456/