Compare dates (stored as string) in android sqlite database?

后端 未结 5 1090
不知归路
不知归路 2020-12-02 19:03

I store dates as String in my database, in this format:

YYYY-MM-DD HH:MM:SS

which is one of supported formats (http://www.sqli

相关标签:
5条回答
  • 2020-12-02 19:42

    if you are storing dates as strings in the format

    YYYY-MM-DD HH:mm:ss  
    

    ====> then your date field is a DateTime datatype

    Thus you have to use such query

    select * 
      from MyTable 
      where mydate >= Datetime('2000-01-01 00:00:00') 
      and mydate <= Datetime('2050-01-01 23:00:59')
    

    you can also use the snippet given by @Joop Eggen with th between operator it's th same approche.

    The BETWEEN operator is logically equivalent to a pair of comparisons. "x BETWEEN y AND z" is equivalent to "x>=y AND x<=z" except that with BETWEEN, the x expression is only evaluated once. see sqlite3 docs

    0 讨论(0)
  • 2020-12-02 19:44

    I think your issue is here...

    AND Datetime(column_date) <= Datetime (2050-01-01))
    

    Why are you using Datetime here instead of Date?

    Try this:

    SELECT  * FROM MyTable WHERE (Date(column_date) >= Date (2000-01-01) AND Date(column_date) <= Date (2050-01-01))
    
    0 讨论(0)
  • 2020-12-02 19:47

    Date filed in the SQLite table will be TEXT and date data should be stored as "2012-12-31 00:12:00" format that comparison dose not give you trouble and if we consider that fields are date_from and date_to and we are storing current date at to_date then we should get the current date as bellow and

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String to_date = sdf.format(new Date());
    

    and the SQL query should be

        crs = db.rawQuery(
          "SELECT _id, date_from, date_to, done_or_not, list_name " +
          "FROM list_tbl " +
          "WHERE " +
          "date_from <= Datetime('"+to_date+"') AND date_to >= Datetime('"+to_date+"')", null);
    
    0 讨论(0)
  • 2020-12-02 19:51
    SELECT *
    FROM MyTable
    WHERE 
        column_date BETWEEN '2000-01-01 00:00:00' AND '2050-01-01 23:00:59'
    

    Should do the trick. This only uses strings but you said that would be fitting.

    The error was the missing time part or not doing a substr on the date part only. And then data/time conversion functions might give wrong things too.

    0 讨论(0)
  • 2020-12-02 19:55

    Compare dates (stored as string) in android SQLite database. Use date in 12/07/2015 format and use a query like this:

    SELECT * FROM tableName WHERE Date >=('12/07/2015') and appointmentDate <('13/07/2015')";
    

    This works for me.

    0 讨论(0)
提交回复
热议问题