通过日期选择器和时间选择器选择日期和时间时,如何在SQLite数据库中存储日期和时间? [英] How can I store Date and Time in SQLite Database when I pick date and time via date picker and time picker?

查看:240
本文介绍了通过日期选择器和时间选择器选择日期和时间时,如何在SQLite数据库中存储日期和时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在选择日期和时间后实现日期选择器时间选择器功能,然后将其存储在 SQLite

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

当前,我正在使用从编辑文本框中获取值来存储日期和时间,并将其转换为字符串并保存为 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()));
}

没有错误。

推荐答案

由于多种原因,将日期存储为字符串不是一个好习惯。例如:如果您要运行查询以根据日期对数据进行排序,如果存储正确,可以直接输入 ORDER BY date,但保留Strings则不允许这样做。可以在这里找到更详细的说明:为什么不应该将日期作为字符串保留在数据库中

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:

如果您正在使用ROOM

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

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

}

现在我们需要定义一个typeConverter对于ROOM将使用的Java的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);
    }

}

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

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

}

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

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

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.

这篇关于通过日期选择器和时间选择器选择日期和时间时,如何在SQLite数据库中存储日期和时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆