比较sqlite中的日期,以毫秒为单位

时间:2017-03-17 05:42:23

标签: java android sqlite jodatime

我在SQLite中有一个表,其日期列定义为Numeric类型

KEY_DRIVER_STAT_DAT + " NUBMERIC" 

现在我在KEY_DRIVER_STAT_DAT列中插入数据

values.put(KEY_DRIVER_STAT_DAT, DateTime.now().getMillis());

如何从此表中获取KEY_DRIVER_STAT_DAT之间的记录 Current date

1 个答案:

答案 0 :(得分:0)

以毫秒值处理日期非常棘手。当您插入具有毫秒值的记录作为日期时,将其插入当前时刻的值。您需要搜索从日期开始(00:00时间)到日期结束(23:59时间)的所有时间段内的记录。看一下这个例子:

/*Suppose your DateTime is Joda's DateTime class*/
import java.util.*;
import org.joda.time.*;

// Two functions to help retrive start and end of date
public static DateTime getStart(DateTime date) {
    return new DateTime(date.year().get(), date.monthOfYear().get(), date.dayOfMonth().get(), 0, 0);    
}
public static DateTime getEnd(DateTime date) {
    return new DateTime(date.year().get(), date.monthOfYear().get(), date.dayOfMonth().get(), 23, 59);  
}

// Code to make clause and parameters for select-statement

DateTime now = DateTime.now();
DateTime start = getStart(now);
DateTime end = getEnd(now);
String yourClause = "KEY_DRIVER_STAT_DAT >= ? AND KEY_DRIVER_STAT_DAT <= ?";
String[] params = new String[] {String.valueOf(start.getMillis()), String.valueOf(end.getMillis())}; 
System.out.println("clause: " + yourClause);
System.out.println("parameters: " + Arrays.toString(params));