Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetching Date from Sqlite Database in android

Tags:

android

sqlite

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

like image 436
Deepak Kataria Avatar asked Jan 10 '13 10:01

Deepak Kataria


People also ask

How to get date from SQLite database?

The SQLite function DATE('now') returns the current date as a text value. It uses the 'YYYY-MM-DD' format, where YYYY is a 4-digit year, MM is a 2-digit month, and DD is a 2-digit day of the month. This function takes one argument: the text 'now' indicates the current date and time.

Does SQLite have date?

SQLite does not have a storage class set aside for storing dates and/or times. Instead, the built-in Date And Time Functions of SQLite are capable of storing dates and times as TEXT, REAL, or INTEGER values: TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS. SSS").

What is the date format in SQLite?

The date() function returns the date as text in this format: YYYY-MM-DD. The time() function returns the time as text in this format: HH:MM:SS.

What is SQLite used for?

SQLite is used to develop embedded software for devices like televisions, cell phones, cameras, etc. It can manage low to medium-traffic HTTP requests. SQLite can change files into smaller size archives with lesser metadata. SQLite is used as a temporary dataset to get processed with some data within an application.


1 Answers

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.

like image 79
TNR Avatar answered Sep 22 '22 13:09

TNR