LoginSignup
1
2

More than 5 years have passed since last update.

SQLiteで日付を扱う方法

Last updated at Posted at 2018-01-25

概要

ミリ秒を取得

INTEGER型でデータベースに格納

cursor.getLong(position)でミリ秒取得

ミリ秒→Stringに変換(SimpleDateFormat, Dateクラスを使用)

サンプルコード

DatePickerDialogで日付を選択 → データベースに格納 → データベースの内容を表示するアプリです
(コードは抜粋)

public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    // CalendarにDatePickerDialogの内容を入れる
    Calendar ms_cal = Calendar.getInstance();
    ms_cal.set(Calendar.YEAR, year);
    ms_cal.set(Calendar.MONTH, month);
    ms_cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    // Calendarからミリ秒を取得
    long ms = ms_cal.getTimeInMillis();
    // ミリ秒をデータベースに格納
    insertLong(ms, TB_DATES);
}
private String msToString(long ms){
    String str;
    Date date = new Date(ms);
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
    str = formatter.format(date);
    return str;
}
    private long stringToMs(String str){
        DateFormat df= new SimpleDateFormat("yyyy/MM/dd");
        long ms = 0;
        try {
            ms = df.parse(str).getTime();
        } catch (ParseException e) {
            Log.d("exception", "sdf parse exception", e);
        }
        return ms;
    }

日付の加減算はミリ秒でした方がCalendar使うより楽かも…?

long dayMs = (long)(1000 * 60 * 60 * 24);

参考文献

http://oki2a24.com/2015/04/19/use-date-with-java-with-sqlite-in-android/
https://www.sejuku.net/blog/20994#yyyyMMdd

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2