在Android中的Sqlite数据库中存储日期和时间以便轻松执行日期操作的最佳方法

时间:2016-07-11 16:31:02

标签: android sqlite date time

我想在Android上存储用户通过日期选择器和时间选择器选择的日期和时间。通过阅读各种线程,我得出结论以INTEGER格式存储日期和时间。所以我使用以下函数将它们转换为long值,但是当我将它们转换回Date时,它给了我错误的日期。

private DatePickerDialog.OnDateSetListener startDatePickerListener = new DatePickerDialog.OnDateSetListener(){

    @Override
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        String dateText = getTimeString(year,monthOfYear,dayOfMonth);
        //Converting Date to long so that can be stored in DB
        long date = Utility.getDateLong(year,monthOfYear,dayOfMonth);
        taskModel.setStartDate(date);
        startDateView.setText(dateText);
    }
};

 public static long getDateLong(int year, int month, int day){
    Calendar cal = new GregorianCalendar(year, month, day);
    long timeStamp = (cal.getTimeInMillis()+cal.getTimeZone().getOffset(cal.getTimeInMillis()))/1000;
    return timeStamp;
}

要将长值转换回日期,我使用以下函数:

public static String getDateFromLongValue(long d){
    Date date = new Date(d);
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    String formattedDate = dateFormat.format(date);
    return formattedDate;
}

但这给了我与输入值不同的日期。有没有其他方法可以做到这一点。我基本上需要比较日期并找出两个日期之间的时间?

1 个答案:

答案 0 :(得分:1)

I suggest a duplicate because while "best way" is theoretically debatable, SQLite offers date functions based on the fact that SQLite doesn't have a time and date type, but does offer date functions based ISO-formatted TEXT timestamp.

One item that is definitely not a matter of opinion though is where you want to do the bulk of operations. You have two choices:

  1. Query for a large amount of data then filter that in your app
  2. Query for a subset of that data

You might will run into timing and memory issues if you don't pre-filter your dataset via the query (i.e. using date and time functions off an ISO-formatted text timestamp) and opt to transform epochs in Java.