Bubunyo Nyavor
Bubunyo Nyavor

Reputation: 2570

Store and retrieve and display current date and time in sqlite database

My title says it all, how best can i store current date and time in a sqlite database and retrieve and display the way i want like 3:45 pm, 20th Jan, 2014 in android?

Upvotes: 0

Views: 1111

Answers (1)

AJ Macdonald
AJ Macdonald

Reputation: 436

Use a Calendar object and store it as a 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.

Upvotes: 2

Related Questions