Retrieve date wise data from database in Android

后端 未结 2 417
梦如初夏
梦如初夏 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.

    0 讨论(0)
  • 2021-01-07 05:13

    Android doesn't have a bulit in data type as "Date". You can either store it as string and parse it appropriately when you use it. So with this option, unless you retrive and parse the Date , you won't be able to find the records in current month.

    Other option is you store it as number - Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

    With some calculation in the where clause you can find out the records for the current month.

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