get Formatted Date from Cursor - Android Database

Android examples for Database:Cursor Get

Description

get Formatted Date from Cursor

Demo Code


//package com.java2s;
import java.util.Calendar;
import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;
import android.text.format.DateUtils;

public class Main {
    public static String getFormattedDate(Cursor cursor, Context context,
            int columnIndex) {
        return getFormattedDate(cursor, context, columnIndex,
                DateUtils.FORMAT_SHOW_DATE);
    }/*from   w  w  w . ja v a2s . co  m*/

    private static String getFormattedDate(Cursor cursor, Context context,
            int columnIndex, int flags) {
        String date = cursor.getString(columnIndex);
        if (!TextUtils.isEmpty(date)) {
            int year = Integer.parseInt(date.substring(0, 4));
            int month = Integer.parseInt(date.substring(5, 7)) - 1;
            int day = Integer.parseInt(date.substring(8, 10));
            Calendar c = Calendar.getInstance();
            c.set(year, month, day);
            return DateUtils.formatDateTime(context, c.getTimeInMillis(),
                    flags);
        }
        return null;
    }

    public static String getString(Cursor cursor, String columnName) {
        return getString(cursor, columnName, "");
    }

    public static String getString(Cursor cursor, String columnName,
            String defaultValue) {
        int idx = cursor.getColumnIndex(columnName);
        if (idx == -1) {
            return defaultValue;
        } else {
            return cursor.getString(idx);
        }
    }
}

Related Tutorials