从android中的Sqlite数据库中获取日期 [英] Fetching Date from Sqlite Database in android

查看:179
本文介绍了从android中的Sqlite数据库中获取日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Sqlite数据库中,我将日期保存为DATE数据类型.如何从游标中获取该日期?

In my Sqlite DataBase I saved date in a data type DATE. How can i fetch this date from cursor?

推荐答案

SQLite使用ISO8601日期/时间格式将表示当前时间的字符串存储在UTC(GMT)中.顺便说一下,此格式(YYYY-MM-DD HH:MM:SS)适合用于日期/时间比较.

SQLite stores a string representing the current time in UTC (GMT), using the ISO8601 date/time format. This format (YYYY-MM-DD HH:MM:SS), is by the way suitable for date/time comparisons.

使用以下代码检索日期.

Use the below code to retrieve the date.

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));

这将返回一个字符串,将其解析并重新格式化为您的本地格式和时区:

This, returns a string, parse it and reformat to your local format and time zone:

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);

希望这会对您有所帮助.

Hope this will help you.

这篇关于从android中的Sqlite数据库中获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆