I’m writing an application where users enter some details into an SQLite Database. I need to write code whereby the last 31 days of stored data in the database is outputted.
The code to save the date string is:
currentDateString = DateFormat.getDateInstance().format(new Date());
This gives the date in the format (for todays date) as 30 Mar 2012.
Is there anyway to change this data format into DD/MM/YYYY? (30/03/2012)
This string is saved into the SQL Database as follows:
ContentValues dbcv = new ContentValues();
dbcv.put(KEY_DATE, date);
(currentDateTime String = Date in previous class)
I wish to output every row of the database that comes within the last 31 days.
How can I do this?
Thanks!
First of all, you are doing two questions instead on just one, I will try to give you an answer to both.
dd/MM/yyyyselectoperation to your table using the date functions provided by SQLLite. Take a look a this webpage as it will give you an idea of what you can do with those functions: SQLLite Date FunctionsNote: Of course, if you still want to store them as strings the only solution you will have is read all the records, parse all the strings back to dates and use the
java.util.Calendarclass to check which record is older than 31 days and which one is not. I’d rather do the SQL query instead of that as it has too much better performance (specially on a mobile device).EDIT:
SQLLite and Android are not specifically my strengths, I did a small research and I found several posts in which people were actually storing them as strings as you initially started to do. If SQLLite on Android doesn’t support storing dates as they are (as other databases do) then maybe the best option in your scenario is using a
longvalue as the date. Look at theDatedefinition class, it has a methodgetTimethat returns the date value as long value, you can use that value later to create a new instance of a date (using its constructor).To format that date (the
Dateobject, of course) in something readable by the user,DateFormat(or any of its implementations) is still the answer.To do the query you want to do having dates stored as longs I suggest you to take a look to the
DateUtilsclass from the Apache Commons Lang library. In that class you will find several functions that work on dates, so, before creating the query you need to fetch the rows in last 31 dates, you could use something like:Hope this helps.