我在SQLite表中有以非标准日期格式存储的日期。我需要能够通过它们进行查询。例如,今天日期的记录在“日期”列中为11/1/2015
,在“sortDate”列中为2015-11-1
。
我的查询需要返回过去一周的记录数。以下内容不返回任何内容:SELECT count(*) FROM Grades WHERE sortDate BETWEEN '2015-10-24' AND '2015-11-02'
我也从SELECT count(*) FROM Grades WHERE sortDate BETWEEN datetime('now', '-7 days') AND datetime('now')
我认为问题是我的日期不会填充为始终有2个月或日期数字,如YYYY-MM-DD
。如何使用这些非标准格式查询现有数据?
答案 0 :(得分:1)
作为Sqlite doesn't have a date type,您需要进行字符串比较才能实现此目的。要做到这一点,你需要扭转顺序 - 例如从dd / MM / yyyy到yyyyMMdd,使用像
这样的东西where substr(column,7)||substr(column,4,2)||substr(column,1,2)
between '20101101' and '20101130'
答案 1 :(得分:0)
我最终从数据库中获取所有日期字符串并使用Java处理它们。我只需要计算过去一周,过去两周和过去一个月内有多少条目。我编写了以下函数来根据提供的字符串ArrayList返回这些计数。
Calendar today = Calendar.getInstance();
Calendar tomorrow = (Calendar) today.clone();
tomorrow.add(Calendar.DATE, 1);
Calendar backDateWeek = (Calendar) today.clone();
backDateWeek.add(Calendar.DATE, -7);
Calendar backDateTwoWeeks = (Calendar) today.clone();
backDateTwoWeeks.add(Calendar.DATE, -14);
Calendar backDateMonth = (Calendar) today.clone();
backDateMonth.add(Calendar.DATE, -30);
ArrayList<Calendar> calendarList = new ArrayList<Calendar>();
Calendar tmpCal;
String strSplit[];
int month;
int day;
int year;
int countWeek = 0;
int countTwoWeeks = 0;
int countMonth = 0;
for (String dateStr : dateStrings) {
strSplit = dateStr.split("/");
month = Integer.parseInt(strSplit[0]) - 1;
day = Integer.parseInt(strSplit[1]);
year = Integer.parseInt(strSplit[2]);
tmpCal = Calendar.getInstance();
tmpCal.set(Calendar.YEAR, year);
tmpCal.set(Calendar.MONTH, month);
tmpCal.set(Calendar.DAY_OF_MONTH, day);
if (tmpCal.after(backDateWeek) && tmpCal.before(tomorrow)) {
countWeek++;
countTwoWeeks++;
countMonth++;
} else if (tmpCal.after(backDateTwoWeeks) && tmpCal.before(tomorrow)) {
countTwoWeeks++;
countMonth++;
} else if (tmpCal.after(backDateMonth) && tmpCal.before(tomorrow)) {
countMonth++;
}
}
int[] countsArray = new int[3];
countsArray[0] = countWeek;
countsArray[1] = countTwoWeeks;
countsArray[2] = countMonth;
return countsArray;