/ / Зберігати та отримувати поточну дату та час у базі даних sqlite - android, sqlite, datetime

Зберігайте і відновіть поточну дату та час у базі даних sqlite - android, sqlite, datetime

У моєму заголовку все це говорить, як краще я можу зберегти поточну дату та час у базі даних sqlite і отримати та показати спосіб, яким я хотів би, наприклад, 3:45 вечора, 20 січня 2014 року в android?

Відповіді:

1 для відповіді № 1

Використовуйте об'єкт календаря та зберігайте його як довгий.

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.