Date comparisons in SQLite on Android
I have been tripped up a few times using date comparisons in SQLite. This is where I pass in a correctly formatted date string and want rows from the database which are equal to this for example.
I get this to work in a couple of steps:
This ensures that everything that gets into my database is correctly formatted for the next bit.
2. In my sql statement I take out the date = string stuff and replace it with a static call to this method:
public static String dbDateCompare(String columnName, String dateValue) {
return "strftime('%Y-%m-%d', " + columnName + ") = '"
+ dateValue + "'";
}
This uses the strftime sqlite function to get the date from the db in a format that is string comparable to the date string passed in.
References:
SQLite date and time function: http://www.sqlite.org/lang_datefunc.html
The JDK 7 version of SimpleDateFormat: http://download.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
I get this to work in a couple of steps:
1. Every date I put in the database goes through this method. It tries to parse the date according to a pattern I have defined and if the date wont parse, returns a null.
public static String dateForDb(String date) {
public static String dateForDb(String date) {
String formattedDate = null;
try {
Date d = null;
d = DateFactory.SDF_SHORT.parse(date);
if (d != null) {
formattedDate = DateFactory.SDF_SHORT.format(d);
}
} catch (Exception e) {
e.printStackTrace();
}
return formattedDate;
}
This ensures that everything that gets into my database is correctly formatted for the next bit.
2. In my sql statement I take out the date = string stuff and replace it with a static call to this method:
public static String dbDateCompare(String columnName, String dateValue) {
return "strftime('%Y-%m-%d', " + columnName + ") = '"
+ dateValue + "'";
}
This uses the strftime sqlite function to get the date from the db in a format that is string comparable to the date string passed in.
public static final SimpleDateFormat SDF_SHORT = new SimpleDateFormat(
"yyyy-MM-dd");
References:
SQLite date and time function: http://www.sqlite.org/lang_datefunc.html
The JDK 7 version of SimpleDateFormat: http://download.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Comments
Post a Comment