Search code examples
androidsortingandroid-sqliteandroid-dateandroid-query

how to sort date which stored in database with string


I am trying to sort

SELECT * FROM myTable ORDER BY DATE(date) // date is stored with string

Here is the LogCat

11-22 12:50:50.906: I/DB(31388): get :17 Nov 2013 09:36:01
11-22 12:50:50.906: I/DB(31388): get :13 Nov 2013 07:41:29
11-22 12:50:50.907: I/DB(31388): get :12 Nov 2013 11:09:46
11-22 12:50:50.907: I/DB(31388): get :08 Nov 2013 09:13:26
11-22 12:50:50.908: I/DB(31388): get :02 Nov 2013 08:54:26
11-22 12:50:50.908: I/DB(31388): get :27 Oct 2013 08:02:09
11-22 12:50:50.908: I/DB(31388): get :26 Oct 2013 07:42:18
11-22 12:50:50.908: I/DB(31388): get :21 Oct 2013 06:45:18
11-22 12:50:50.909: I/DB(31388): get :19 Oct 2013 07:38:43
11-22 12:50:50.909: I/DB(31388): get :16 Oct 2013 03:12:16

UPDATE from HERE============>>>

This is not return long value. It is always return 0.

    try {
        DateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        Date date = sdf.parse(dateTime);
        long milliseconds = date.getTime();
        return milliseconds;
    } catch (Exception e) {
        e.printStackTrace();
        Log.i("DB", "err :" + e);
        return 0;
    }

I want to sort with latest date can anyone spent some time for me.. Thanks in advance.


Solution

  • You can convert you string date into Long Then Put up it into Database: if you have Date String something like this 22/11/2013 12:10:00 you can simply convert it with the help of SimpleDateFormater

       public static long convertStringDateToLong(String dateTime){
            try {
                DateFormat f = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
                Date d = f.parse(dateTime);
                long milliseconds = d.getTime();
                return milliseconds;
            } catch (Exception e) {
                return 0;
            }
    
        }
    

    SimpleDateFormate Depends on you Date String formate.