How Can I Store Date And Time In Sqlite Database When I Pick Date And Time Via Date Picker And Time Picker?
Solution 1:
It is not a good practice to store dates as Strings due to a number of reasons. e.g: If you want to run a Query to sort your data based on dates you could just go "ORDER BY date" if you stored it properly, but keeping Strings wont allow this. A more detailed explanation can be found here : Why you shouldnt keep dates as Strings in Database
So, a much better way to keep dates would be:
If you are using ROOM
For the Entity Classes keep date as java.util.Date type. Like below:
@Entity(tableName = NoteConstants.TABLE_NAME)
publicclassNote {
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = NoteConstants.ATTR_ID)
private int id;
@ColumnInfo(name = NoteConstants.ATTR_DESCRIPTION)
privateString description;
@ColumnInfo(name = NoteConstants.ATTR_DATE)
privateDate date;
publicNote(String description) {
this.description = description;
this.date = newDate();
}
public int getId() {
return id;
}
publicvoidsetId(int id) {
this.id = id;
}
publicStringgetDescription() {
return description;
}
publicDategetDate() {
return date;
}
publicvoidsetDate(Date date) {
this.date = date;
}
}
Now We need to define a typeConverter for Java's Date type which ROOM will use:
import androidx.room.TypeConverter;
import java.util.Date;
publicclassDateConverter {
@TypeConverterpublicstatic long toTimeStamp(Date date){
return date == null? null : date.getTime();
}
@TypeConverterpublicstaticDatetoDate(Long timeStamp){
return timeStamp == null ? null : newDate(timeStamp);
}
}
finally, we need to specify the type converters in the ROOM @Database class using @TypeConverters:
@Database(entities = {Note.class}, version = 1)@TypeConverters(DateConverter.class)publicabstractclassNoteDatabaseextendsRoomDatabase {
privatestaticStringDB_NAME="note_database";
privatestatic NoteDatabase instance;
publicabstract NoteDAO getNoteDao();
publicstaticsynchronized NoteDatabase getInstance(Context context) {
if (instance == null) {
instance = Room.databaseBuilder(context.getApplicationContext(),
NoteDatabase.class, DB_NAME)
.fallbackToDestructiveMigration()
.build();
}
return instance;
}
}
If you are not using ROOM and using raw SQLite openHelper:
Just keep the long timestamp in the database and use the type conversion methods we built above manually to get the Date from the long timestamp and vice versa.
Post a Comment for "How Can I Store Date And Time In Sqlite Database When I Pick Date And Time Via Date Picker And Time Picker?"