Search code examples
javaandroidsqliteandroid-sqlitequery-string

Why my SQLite request in java code output only months from October(&&/10/&&)?


Case: In my SQLite database date store as DATE type. Iam trying to show records from current month and if that month is 10, 11 or 12 everything is working but month from 1 to 9 is giving empty output.

'''

    LocalDate ld = LocalDate.now();
    int yearNumber = ld.getYear();
    int monthNumber = ld.getMonth().getValue();

    String queryString = "SELECT " +
            " *, " +
            "strftime('%m', DAY_DATE) as Month, " +   //  getting number of month from 01 to 12 
            "strftime('%Y', DAY_DATE) as Year   " +   // getting number of year
            " FROM " + DAYS_TABLE +
            " WHERE "+"Month" +
            " LIKE "  + monthNumber +
            " AND " + "Year"+
            " LIKE " + yearNumber +
            " ORDER BY " + COLUMN_DAY_DATE +
            " DESC " ;

'''

What should i use to see records from each month?


Solution

  • The function strftime() returns a string and not a number, so strftime('%m', DAY_DATE) may return 05 and not 5.
    If you want to compare it with a number you must convert it and this can be done implicitly by adding 0.
    So change to:

     " WHERE (Month + 0) = "  + monthNumber +
     " AND (Year + 0) = " + yearNumber +
     " ORDER BY " + COLUMN_DAY_DATE +
     " DESC " ;