I use room database
and want to save date in database.
I want to save date with this format "dd/MM/yy"
to database.
So i create DateConverter
class to written from/into the database.
Now i can save date with my favorite format into the database but i can't get date from database with my favorite format and when i get the date gives me all info of Date(date , time ,day).
I can use toTimestamp
method from DateConverter
but i think is not good idea.
I want to know is there a way to get date directly without using 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;
}
DateConverter
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
@Dao
public interface NoteDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<NoteEntity> noteEntity);
@Query("SELECT * FROM notes")
List<NoteEntity> loadAllNotes();
}
Sample Data
public static List<NoteEntity> getNotes() {
List<NoteEntity> notes = new ArrayList<>();
notes.add(new NoteEntity(new Date(2019,8,5), SAMPLE_TEXT_1));
.
.
.
return notes;
}
Main
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