Fetching Date from Sqlite Database in android

后端 未结 3 1481
青春惊慌失措
青春惊慌失措 2021-02-05 17:05

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

3条回答
  •  后悔当初
    2021-02-05 17:24

    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.

提交回复
热议问题