在我的 Sqlite 数据库中,我将日期保存在数据类型 DATE 中。如何从光标中获取此日期?
问问题
36295 次
3 回答
16
SQLite 使用 ISO8601 日期/时间格式以 UTC (GMT) 存储表示当前时间的字符串。顺便说一下,这种格式 (YYYY-MM-DD HH:MM:SS) 适用于日期/时间比较。
使用以下代码检索日期。
Cursor row = databaseHelper.query(true, TABLE_NAME, new String[] {
COLUMN_INDEX}, ID_COLUMN_INDEX + "=" + rowId,
null, null, null, null, null);
String dateTime = row.getString(row.getColumnIndexOrThrow(COLUMN_INDEX));
这将返回一个字符串,对其进行解析并重新格式化为您的本地格式和时区:
DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = iso8601Format.parse(dateTime);
} catch (ParseException e) {
Log.e(TAG, "Parsing ISO8601 datetime failed", e);
}
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;
String finalDateTime = android.text.format.DateUtils.formatDateTime(context,
when + TimeZone.getDefault().getOffset(when), flags);
希望这会帮助你。
于 2013-01-10T10:43:58.877 回答
13
SQLite 并没有真正的DATE
类型(DATE
关键字只是表示该列具有NUMERIC
亲和性,根据SQLite 版本 3 中的数据类型),因此您可以选择存储日期的约定。常见约定是 (a) 使用实数来存储儒略日期或 (b) 使用整数来存储 Unix 纪元(自 1970 年以来的秒数,SQLite 日期和时间函数支持每个日期和时间的 'unixepoch' 参数)功能)。
如果您正在将日期存储为 Unix 纪元(对于 Android 来说很方便,因为调用.getTime()
一个Date
对象会返回自 1970 年以来的毫秒数),然后将 SQLiteDATE
字段读取为 along
并将其等效的毫秒传递给java.util.Date
构造函数Date(long milliseconds)
。所以,它看起来像这样:
SQLiteManager dbManager = new SQLiteManager(context, DB_NAME, null, VERSION);
SQLiteDatabase db = dbManager.getReadableDatabase();
Cursor cursor = db.query(TABLE_NAME,
new String[] { COLUMN_NAME_ID, COLUMN_NAME_DATE },
null, null, // selection, selectionArgs
null, null, null, null); // groupBy, having, orderBy, limit
try {
while(cursor.moveNext()) {
int id = cursor.getInt(0);
// Read the SQLite DATE as a long and construct a Java Date with it.
Date date = new Date(cursor.getLong(1)*1000);
// ...
}
} finally {
cursor.close();
db.close();
}
于 2013-07-28T06:44:37.623 回答
4
此代码有效
String s= cursor.getString(position);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date d=new Date();
try {
d= dateFormat.parse(s);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
YourObject.setDate(d);
于 2013-01-10T11:00:34.973 回答