查询不同格式的SQLite日期

问题描述:

我有一个存储在非标准日期格式的SQLite表中的日期。我需要能够由他们查询。例如,今天的日期记录在“日期”列中为11/1/2015,在“sortDate”列中为2015-11-1查询不同格式的SQLite日期

我的查询需要返回过去一周的记录数。下面返回任何: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。我将如何查询这些非标准格式的现有数据?

由于Sqlite doesn't have a date type你需要做字符串比较来实现这一点。对于工作,你需要扭转的顺序 - 例如从DD/MM/YYYY至年月日,使用类似

where substr(column,7)||substr(column,4,2)||substr(column,1,2) 
     between '20101101' and '20101130' 
+0

我想我明白你在说什么,但我的日期有时是'YYYY-MM-DD'有时'YYYY-M-D',根据不同的月份和日期是否是1位或2位。所以我不会总是知道子字符串的索引。 – NSouth

+0

如果月份或日期小于10,您可以只添加0值吗?但在此之前,我需要知道你是如何得到日期的 –

+0

我该如何在查询中做到这一点?或者我必须得到一个字符串结果的列表,将它们转换为java中的日期,然后编写一个函数来“过滤”该列表并返回计数?我希望我可以在sqlite查询中完成所有这些。 – NSouth

我结束了从数据库中获取所有日期字符串,并与他们在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;