在android sqlite中基于当前时间在表格字段中显示总线时间的值

问题描述

我的问题是我需要基于“总线时间”字段显示数据库中的所有数据,并与当前时间进行比较,即如果当前时间为6:30 PM,则它应该显示所有“总线时间”字段大于或等于当前时间(6:30)的值。

我已经在android studio的DatabaseHandler.java中编写了一个SQL查询,但是查询中出现错误,请您帮忙解决它。

查询代码

public List<Contact> getBus(String t)
    {
        List<Contact> contactList = new ArrayList<Contact>();
        String query = "SELECT * FROM contacts WHERE CAST( bus_time AS TIME ) >= CAST(" + t +" AS TIME )";
        sqliteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(query,null);
        

        // looping through all rows and adding to list
        if (cursor.movetoFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.movetoNext());
        }

        // return contact list
        return contactList;


    }

我遇到的错误

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.database,PID: 4539
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.database/com.example.database.MainActivity}: android.database.sqlite.sqliteException: near ":27": Syntax error (code 1):,while compiling: SELECT * FROM contacts WHERE CAST( bus_time AS TIME ) >= CAST(18:27 AS TIME )
        at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2646)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6077)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
    

解决方法

在SQLite中,没有数据类型TIME,任何日期和/或时间值都应视为TEXT
使用函数STRFTIME()HH:MM格式获取当前时间:

SELECT * 
FROM contacts 
WHERE SUBSTR('0' || bus_time,-5) >= STRFTIME('%H:%M','now','localtime')

如果您将时间保存在bus_time列中,格式为HH:MM(小时为2位数字),则不需要使用SUBSTR()左边的{ {1}}(如果小时只有1位数字,并且代码为:

0