我的标题说明了这一点,我如何最好地将当前日期和时间存储在sqlite数据库中,并检索并显示我想要的方式,如2014年1月20日下午3:45在android中?
答案 0 :(得分: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.