我在使用SQLite的Android应用程序上处理日期遇到了一些麻烦。 我有几个问题:
我应该使用什么类型存储日期在SQLite(文本,整数,…)? 给出了存储日期的最佳方式,我如何使用ContentValues正确存储它? 从SQLite数据库中检索日期的最佳方法是什么? 如何在SQLite上进行sql选择,按日期排序结果?
我在使用SQLite的Android应用程序上处理日期遇到了一些麻烦。 我有几个问题:
我应该使用什么类型存储日期在SQLite(文本,整数,…)? 给出了存储日期的最佳方式,我如何使用ContentValues正确存储它? 从SQLite数据库中检索日期的最佳方法是什么? 如何在SQLite上进行sql选择,按日期排序结果?
当前回答
最好的方法是将日期存储为使用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()来正确地获取时间戳。
其他回答
最好的方法是将日期存储为使用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()来正确地获取时间戳。
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
通常(与我在mysql/postgres中所做的一样),我将日期存储在int(mysql/post)或文本(sqlite)中,以时间戳格式存储它们。
然后,我将它们转换为日期对象,并根据用户时区执行操作
您可以使用文本字段在SQLite中存储日期。
以UTC格式存储日期,默认情况下,如果使用datetime('now') (yyyy-MM-dd HH:mm:ss)将允许按日期列排序。
从SQLite中检索日期作为字符串,然后使用Calendar或android.text.format.DateUtils.formatDateTime方法将它们格式化/转换为所需的本地区域化格式。
这是我使用的一个区域化格式化器方法;
public static String formatDateTime(Context context, String timeToFormat) {
String finalDateTime = "";
SimpleDateFormat iso8601Format = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
Date date = null;
if (timeToFormat != null) {
try {
date = iso8601Format.parse(timeToFormat);
} catch (ParseException e) {
date = null;
}
if (date != null) {
long when = date.getTime();
int flags = 0;
flags |= android.text.format.DateUtils.FORMAT_SHOW_TIME;
flags |= android.text.format.DateUtils.FORMAT_SHOW_DATE;
flags |= android.text.format.DateUtils.FORMAT_ABBREV_MONTH;
flags |= android.text.format.DateUtils.FORMAT_SHOW_YEAR;
finalDateTime = android.text.format.DateUtils.formatDateTime(context,
when + TimeZone.getDefault().getOffset(when), flags);
}
}
return finalDateTime;
}
在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;
}
希望这对大家有所帮助!:)