Date
正是https://developer.android.com/training/data-storage/room/referencing-data中给出的例子.
For example, if we want to persist instances of Date, we can write the following TypeConverter to store the equivalent Unix timestamp in the database:
public class Converters {
@TypeConverter
public static Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public static Long dateToTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}
The preceding example defines 2 functions, one that converts a Date object to a Long object and another that performs the inverse conversion, from Long to Date. Since Room already knows how to persist Long objects, it can use this converter to persist values of type Date.
接下来,将@TypeConverters注释添加到AppDatabase类,以便Room可以使用您为该AppDatabase中的每个实体和DAO定义的转换器:
AppDatabase.java
@Database(entities = {User.class}, version = 1)
@TypeConverters({Converters.class})
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
旁注:java.util.Date
被认为设计糟糕(java.util.Calendar
更糟).如果您有任何非平凡的日期时间逻辑,并且可以使用API级别26(桌面上的Java 8),通常最好使用java.time
package.如果不能,请参阅https://github.com/JakeWharton/ThreeTenABP了解后端口.