Retrieve date wise data from database in Android

后端 未结 2 438
梦如初夏
梦如初夏 2021-01-07 04:10

In my database I have 1 table with date as one of the column, which stores the date when user add some data in my table.

Now I want to retrieve the data

2条回答
  •  爱一瞬间的悲伤
    2021-01-07 04:55

    If you want to "automatically" load the current year/month, use SQLite's strftime function with 'now' modifier & '%Y-%m' format mask.

    select strftime('%Y-%m', 'now');
    

    Now, coming to your question:

    Now I want to retrieve the data for the current month alone.

    Well, here comes a mess. You can't store the date as a datetime type, instead it's stored as a string in a format SQLite can't parse using date functions. So you'll have to convert it into a format which SQLite can understand.

    You can do that by using the usual substr function

    substr(exp_date, 7) || '-' || substr(exp_date, 4,2) || '-' || substr(exp_date, 1,2)
    

    So this will covert dd/mm/yyyy to YYYY-mm-dd format.

    So the full query will be:

    SELECT *
    FROM   incomexpense
    WHERE  Strftime('%Y-%m', 'now') = Strftime('%Y-%m', Substr(exp_date, 7)
                                                        || '-'
                                                        || Substr(exp_date, 4, 2)
                                                        || '-'
                                                        || Substr(exp_date, 1, 2)) 
    

    See how this works over here.

提交回复
热议问题