且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获得在SQLite数据库以present日期最接近日期

更新时间:2022-10-18 09:32:33

测试:

  SELECT吨。* FROM表t
WHERE t.date_col =
  (SELECT MIN(t2.date_col)从表t
    WHERE t2.date_col> =? );

?参数将值传递是当前日期

如果date_col的数据类型是整数SQLite中,?参数将这个值传递:System.currentTimeMillis的()

注意:您可能需要删除的时间信息,如小时,分,秒,从System.currentTimeMillis的()毫秒

注意2:
 如果你使用字符串作为SQLite的数据类型,你必须System.currentTimeMillis的()格式化到日期格式YYYY / MM / DD。如果使用其他格式,如M / D / YYYY - >您将有日​​期字符串比较的问题。请参阅下面的M / D / yyyy格式的问题:

 2015年5月15日.compareTo(2015年11月30日)--->返回4是H. 0
- >意思是2015年5月15日> 2015年11月30日---错

I have an SQLite database with a table that holds a column full of dates. I need to get the date closest to the present date out of everything in that column, but I don't know how to build a query for this.

For example I have the following dates in the column

3/15/2015
3/31/2015
4/15/2015
4/30/2015
5/15/2015
5/30/2015

If the current date is 4/20/2015 I need it to get all rows that have the date.

EDIT

For clarification I need the only the upcoming dates not the past dates.

4/30/2015

Also my dates are stored as string. Can anyone help?

FINAL QUERY courtesy of Loc Ha

Cursor trythis(String Date) {
    SQLiteDatabase db = this.getReadableDatabase();
    String[] params = new String[]{String.valueOf(Date)};
    Cursor cur = db.rawQuery("SELECT  " + colCompID + " as _id," + colCompClass + "," + colName + "," + colPayDue + "," + colDateDue + " FROM " + viewComps + " WHERE " + colDateDue + "=" + "( SELECT MIN (" + colDateDue + ") FROM " + PAYMENTS + " WHERE " + colDateDue + ">=?);", params);
    return cur;
}

Test this:

SELECT t.* FROM table t
WHERE t.date_col = 
  ( SELECT MIN (t2.date_col) FROM table t2
    WHERE t2.date_col >= ? );

? parameter will be passed with value is CURRENT date

IF date_col data type is Integer in SQLite, ? parameter will be passed with this value: System.currentTimeMillis()

Note: You may have to remove time info such as hour, minute, second, millisecond from System.currentTimeMillis()

Note 2: If you use String as Data type in SQLite, you have to format System.currentTimeMillis() into Date format "yyyy/MM/dd". If you use other formats such as M/d/yyyy --> You will have date String comparing issues. See issue below for M/d/yyyy format:

"5/15/2015".compareTo("11/30/2015") ---> Return 4 > 0
--> means "5/15/2015" > "11/30/2015" --- Wrong