我在使用SQLite的Android应用程序上处理日期遇到了一些麻烦。 我有几个问题:

我应该使用什么类型存储日期在SQLite(文本,整数,…)? 给出了存储日期的最佳方式,我如何使用ContentValues正确存储它? 从SQLite数据库中检索日期的最佳方法是什么? 如何在SQLite上进行sql选择,按日期排序结果?


当前回答

1 -就像StErMi说的。

2 -请阅读:http://www.vogella.de/articles/AndroidSQLite/article.html

3 -

Cursor cursor = db.query(TABLE_NAME, new String[] {"_id", "title", "title_raw", "timestamp"}, 
                "//** YOUR REQUEST**//", null, null, "timestamp", null);

在这里看到的:

查询()在SQLiteDatabase

4 -见答案3

其他回答

我更喜欢这个。这不是最好的方法,但却是一个快速的解决方案。

//Building the table includes:
StringBuilder query= new StringBuilder();
query.append("CREATE TABLE "+TABLE_NAME+ " (");
query.append(COLUMN_ID+"int primary key autoincrement,");
query.append(COLUMN_CREATION_DATE+" DATE)");

//Inserting the data includes this:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
values.put(COLUMN_CREATION_DATE,dateFormat.format(reactionGame.getCreationDate())); 

// Fetching the data includes this:
try {
   java.util.Date creationDate = dateFormat.parse(cursor.getString(0);
   YourObject.setCreationDate(creationDate));
} catch (Exception e) {
   YourObject.setCreationDate(null);
}

最好的方法是将日期存储为使用Calendar命令接收的数字。

//Building the table includes:
StringBuilder query=new StringBuilder();
query.append("CREATE TABLE "+TABLE_NAME+ " (");
query.append(COLUMN_ID+"int primary key autoincrement,");
query.append(COLUMN_DATETIME+" int)");

//And inserting the data includes this:
values.put(COLUMN_DATETIME, System.currentTimeMillis()); 

Why do this? First of all, getting values from a date range is easy. Just convert your date into milliseconds, and then query appropriately. Sorting by date is similarly easy. The calls to convert among various formats are also likewise easy, as I included. Bottom line is, with this method, you can do anything you need to do, no problems. It will be slightly difficult to read a raw value, but it more than makes up that slight disadvantage with being easily machine readable and usable. And in fact, it is relatively easy to build a reader (And I know there are some out there) that will automatically convert the time tag to date as such for easy of reading.

值得一提的是,这个函数的值应该是long,而不是int。sqlite中的整数可以表示很多东西,从1-8字节的任何东西,但对于几乎所有日期来说,64位或长位是可行的。

编辑:正如评论中所指出的,如果要这样做,必须使用cursor.getLong()来正确地获取时间戳。

通常(与我在mysql/postgres中所做的一样),我将日期存储在int(mysql/post)或文本(sqlite)中,以时间戳格式存储它们。

然后,我将它们转换为日期对象,并根据用户时区执行操作

在SQlite DB中存储日期的最佳方法是存储当前的datetimemillisseconds。下面是执行so_的代码片段

获取datetimemillisseconds

public static long getTimeMillis(String dateString, String dateFormat) throws ParseException {
    /*Use date format as according to your need! Ex. - yyyy/MM/dd HH:mm:ss */
    String myDate = dateString;//"2017/12/20 18:10:45";
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);
    Date date = sdf.parse(myDate);
    long millis = date.getTime();

    return millis;
}

在数据库中插入数据

public void insert(Context mContext, long dateTimeMillis, String msg) {
    //Your DB Helper
    MyDatabaseHelper dbHelper = new MyDatabaseHelper(mContext);
    database = dbHelper.getWritableDatabase();

    ContentValues contentValue = new ContentValues();
    contentValue.put(MyDatabaseHelper.DATE_MILLIS, dateTimeMillis);
    contentValue.put(MyDatabaseHelper.MESSAGE, msg);

    //insert data in DB
    database.insert("your_table_name", null, contentValue);

   //Close the DB connection.
   dbHelper.close(); 

}

现在,您的数据(日期在currenttimemillisecseconds中)被插入到DB中。

下一步是,当您想从DB检索数据时,您需要将各自的日期时间毫秒转换为相应的日期。下面是执行相同操作的示例代码片段_

将日期毫秒转换为日期字符串。

public static String getDate(long milliSeconds, String dateFormat)
{
    // Create a DateFormatter object for displaying date in specified format.
    SimpleDateFormat formatter = new SimpleDateFormat(dateFormat/*"yyyy/MM/dd HH:mm:ss"*/);

    // Create a calendar object that will convert the date and time value in milliseconds to date.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(milliSeconds);
    return formatter.format(calendar.getTime());
}

现在,最后获取数据,看看它的工作…

public ArrayList<String> fetchData() {

    ArrayList<String> listOfAllDates = new ArrayList<String>();
    String cDate = null;

    MyDatabaseHelper dbHelper = new MyDatabaseHelper("your_app_context");
    database = dbHelper.getWritableDatabase();

    String[] columns = new String[] {MyDatabaseHelper.DATE_MILLIS, MyDatabaseHelper.MESSAGE};
    Cursor cursor = database.query("your_table_name", columns, null, null, null, null, null);

    if (cursor != null) {

        if (cursor.moveToFirst()){
            do{
                //iterate the cursor to get data.
                cDate = getDate(cursor.getLong(cursor.getColumnIndex(MyDatabaseHelper.DATE_MILLIS)), "yyyy/MM/dd HH:mm:ss");

                listOfAllDates.add(cDate);

            }while(cursor.moveToNext());
        }
        cursor.close();

    //Close the DB connection.
    dbHelper.close(); 

    return listOfAllDates;

}

希望这对大家有所帮助!:)

As presumed in this comment, I'd always use integers to store dates. For storing, you could use a utility method public static Long persistDate(Date date) { if (date != null) { return date.getTime(); } return null; } like so: ContentValues values = new ContentValues(); values.put(COLUMN_NAME, persistDate(entity.getDate())); long id = db.insertOrThrow(TABLE_NAME, null, values); Another utility method takes care of the loading public static Date loadDate(Cursor cursor, int index) { if (cursor.isNull(index)) { return null; } return new Date(cursor.getLong(index)); } can be used like this: entity.setDate(loadDate(cursor, INDEX)); Ordering by date is simple SQL ORDER clause (because we have a numeric column). The following will order descending (that is newest date goes first): public static final String QUERY = "SELECT table._id, table.dateCol FROM table ORDER BY table.dateCol DESC"; //... Cursor cursor = rawQuery(QUERY, null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { // Process results }

始终确保存储UTC/GMT时间,特别是在使用java.util.Calendar和java.text.SimpleDateFormat使用默认(即您的设备的)时区时。 使用java.util.Date.Date()是安全的,因为它创建了一个UTC值。