/ / sqliteデータベースに現在の日付と時刻を格納し、検索して表示する - android、sqlite、datetime

ストアと検索、現在の日付と時刻をsqliteデータベースに表示する - android、sqlite、datetime

私のタイトルはそれをすべて言います、どのように最高のsqliteデータベースに現在の日付と時刻を保存し、私が3:45 pm、2014年1月20日、アンドロイドで好きな方法を取得して表示することができますか?

回答:

回答№1は1

Calendarオブジェクトを使用し、それをlongとして格納します。

Calendar cal = Calendar.getInstance(); // returns Calendar object set to current moment

// store in database: use your own Database class constructor, not "Database(context)"
SQLiteDatabase db = new Database(context).getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("my date column", cal.getTimeInMillis());
db.insert("my table", null, cv);
db.close();

// to retrieve date after using the cursor to get values from database:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cursor.getLong(cursor.getColumnIndexOrThrow("my date column"))); //resets the calendar object to the time stored from database

// display time in log
Log.d("The time is: ", cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE) + " " + (cal.get(Calendar.MONTH) + 1) + "-" + cal.get(Calendar.DAY_OF_MONTH) + "-" + cal.get(Calendar.YEAR));
// the +1 on the month field is because January starts at 0.