通过日期选择器和时间选择器选择日期和时间时,如何在SQLite数据库中存储日期和时间?

时间:2019-10-05 10:07:33

标签: java android sqlite datetime datepicker

我要在选择日期和时间之后将date pickertime picker功能存储在SQLite中吗?

当前,我正在使用从编辑文本框中获取值来存储日期和时间,并将其转换为字符串并保存为SQLite

这样存储日期和时间的方法正确吗?

 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()));
}

没有错误。

1 个答案:

答案 0 :(得分:2)

出于多种原因,将日期存储为字符串不是一个好习惯。例如:如果您要运行查询以根据日期对数据进行排序,如果存储正确,可以直接输入“ ORDER BY date”,但保留String则不允许这样做。可以在以下位置找到更详细的说明:Why you shouldnt keep dates as Strings in Database

因此,保留日期的更好方法是:

如果您使用的是ROOM

对于实体类,将日期保留为java.util.Date类型。如下所示:

@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;
    }

}

现在,我们需要为ROOM将使用的Java的Date类型定义一个typeConverter:

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);
    }

}

最后,我们需要使用@TypeConverters在ROOM @Database类中指定类型转换器:

@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;
    }

}

如果您不使用ROOM而不使用原始SQLite openHelper:

只需将较长的时间戳记保存在数据库中,并使用我们上面手动构建的类型转换方法从较长的时间戳记中获取日期,反之亦然。