Android - SQLite - SELECT BETWEEN Date1 AND Date2

后端 未结 4 1536
暖寄归人
暖寄归人 2020-12-21 06:35

Mac OS-X

Android

Eclipse with ADT

SQLite

I\'m new to creating Android Apps and Ive researched this heavily but I\'m getting nowhere. I need

4条回答
  •  时光取名叫无心
    2020-12-21 07:25

    Ok, so I could not get string dates to work, so I had to convert String Dates to Calendar Dates to Unix Time before adding them to the SQLite database and convert them back (Unix Time to Calendar Dates to String) when displaying them. Unix Time allows calculations (order by, sort ascending, between etc) done on the date columns and it is the best method to use after long hours of trial and error. Here is the code I ended up using:

    Cursor c = newDB.rawQuery("select ID, Date, Hours from " + tableName + " where Date BETWEEN '" + startDateQueryDate + "' AND '" + endDateQueryDate + "' ORDER BY Date ASC", null);
    
                if (c != null ) {
                    if  (c.moveToFirst()) {
                        do {
                            int tempId = c.getInt(c.getColumnIndex("ID"));
                            long tempUnixTime = c.getLong(c.getColumnIndex("Date"));
    
                            //convert tempUnixTime to Date
                            java.util.Date startDateDate = new java.util.Date(tempUnixTime);
    
                            //create SimpleDateFormat formatter
                            SimpleDateFormat formatter1;
                            formatter1 = new SimpleDateFormat("dd/MM/yyyy", Locale.UK);
    
                            //convert Date to SimpleDateFormat and convert to String
                            String tempStringStartDate = formatter1.format(startDateDate);
    
                            int tempHours = c.getInt(c.getColumnIndex("Hours"));
                            results.add(+ tempId + "    Date: " + tempStringStartDate + "    Hours: " + tempHours);
                        }while (c.moveToNext());
                    }
                }
    

提交回复
热议问题