【发布时间】:2019-12-14 16:40:32
【问题描述】:
我使用room database 并希望将日期保存在数据库中。
我想用这种格式"dd/MM/yy" 将日期保存到数据库中。
所以我创建了DateConverter 类来写入/写入数据库。
现在我可以将日期以我最喜欢的格式保存到数据库中,但我无法从数据库中以我最喜欢的格式获取日期,当我得到日期时,我会提供日期的所有信息(日期、时间、日期)。
我可以使用DateConverter 中的toTimestamp 方法,但我认为这不是一个好主意。
我想知道有没有办法不使用DateConverter.toTimestamp直接获取日期。
@Entity(tableName = "notes")
public class NoteEntity {
@PrimaryKey(autoGenerate = true)
private int id;
private Date date;
private String text;
@Ignore
public NoteEntity() {
}
public NoteEntity(int id, Date date, String text) {
this.id = id;
this.date = date;
this.text = text;
}}
@Ignore
public NoteEntity(Date date, String text) {
this.date = date;
this.text = text;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
日期转换器
public class DateConverter {
@TypeConverter
public static Date toDate(String stringdate){
return stringdate == null ? null : new Date(stringdate);
}
@TypeConverter
public static String toTimestamp(Date date){
SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yy");
return dateTimeFormat.format(date);
}
}
道
@Dao
public interface NoteDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<NoteEntity> noteEntity);
@Query("SELECT * FROM notes")
List<NoteEntity> loadAllNotes();
}
样本数据
public static List<NoteEntity> getNotes() {
List<NoteEntity> notes = new ArrayList<>();
notes.add(new NoteEntity(new Date(2019,8,5), SAMPLE_TEXT_1));
.
.
.
return notes;
}
主要
AppDatabase appDatabase = AppDatabase.getInstance(context);
appDatabase.noteDao().insertAll(getNotes());
List<NoteEntity> notesData = new ArrayList<>();
notesData = appDatabase.noteDao().loadAllNotes();
Log.i("TestOutput1", String.valueOf(notesData.get(0).getDate()));
Log.i("TestOutput2", DateConverter.toTimestamp(notesData .get(0).getDate()));
LogCat
I/TestOutput1: Mon Aug 05 00:00:00 GMT+04:30 2019
I/TestOutput2: 05/08/19
【问题讨论】:
-
您需要使用
SimpleDateFormat将您在@TypeConverter方法中输入的日期转换为您想要的格式,以便保存您想要的日期。 -
stackoverflow.com/a/27482709/7316510此链接可能会帮助您实现您的要求。
标签: android sqlite android-sqlite android-room android-database