How can I store Date and Time in SQLite Database when I pick date and time via date picker and time picker?

和自甴很熟 提交于 2020-01-24 21:10:50

问题


I am implementing date picker and time picker functionality after pick date and time I want to store it in SQLite ?

Currently I am storing Date and Time using getting value from edit text box and convert into String and Save into SQLite.

Is this right way to store date and time like this ?

 EditText Reminder_Time,Followup_date;

  Reminder_Time.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar mcurrentTime = Calendar.getInstance();
            int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
            int minute = mcurrentTime.get(Calendar.MINUTE);

            TimePickerDialog mTimePicker;
            mTimePicker = new TimePickerDialog(Activity_Add_Followup.this, new TimePickerDialog.OnTimeSetListener() {
                @Override
                public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
                    Reminder_Time.setText( selectedHour + ":" + selectedMinute);
                }
            }, hour, minute, false);
            mTimePicker.setTitle("Select Time");
            mTimePicker.show();
            Reminder_Time.setEnabled(true);
        }


    });
     Followup_date.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View view) {
             new DatePickerDialog(Activity_Add_Followup.this, date, myCalendar
                     .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                     myCalendar.get(Calendar.DAY_OF_MONTH)).show();

             Followup_date.setEnabled(true);
         }
     });

final Calendar myCalendar = Calendar.getInstance();

DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear,
                          int dayOfMonth) {
        // TODO Auto-generated method stub
        myCalendar.set(Calendar.YEAR, year);
        myCalendar.set(Calendar.MONTH, monthOfYear);
        myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        updateLabel();
    }

};



private void updateLabel() {
    String myFormat = "yyyy/MM/dd"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

    Followup_date.setText(sdf.format(myCalendar.getTime()));
}

No errors.


回答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)
public class Note {
    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = NoteConstants.ATTR_ID)
    private int id;

    @ColumnInfo(name = NoteConstants.ATTR_DESCRIPTION)
    private String description;

    @ColumnInfo(name = NoteConstants.ATTR_DATE)
    private Date date;

    public Note(String description) { 
        this.description = description;
        this.date = new Date();
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDescription() {
        return description;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(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;

public class DateConverter {

    @TypeConverter
    public static long toTimeStamp(Date date){
        return date == null? null : date.getTime();
    }

    @TypeConverter
    public static Date toDate(Long timeStamp){
        return timeStamp == null ? null : new Date(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)
public abstract class NoteDatabase extends RoomDatabase {

    private static String DB_NAME = "note_database";
    private static NoteDatabase instance;

    public abstract NoteDAO getNoteDao();

    public static synchronized 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.



来源:https://stackoverflow.com/questions/58247286/how-can-i-store-date-and-time-in-sqlite-database-when-i-pick-date-and-time-via-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!