我想查询SQLite表并获取记录,其中时间字段(以毫秒为单位表示长时间的字符串)在查询时间的明天范围内。
我还有一个字段,它保存记录日期时间如下:
dd / MM / yyyy,HH:mm:ss
您如何推荐实施此功能?
答案 0 :(得分:3)
根据您的评论,您可以修改架构以获得更好的性能。因此,最好在数据库中保存时间(unix timestamp)并在其上设置索引。完成后,您可以简单地在当地时区的00:00获取明天的日期,并将其转换为unix时间戳并基于此进行查询。这是你如何在00:00获得明天的时间戳,
public static long getTimeStampAt0000(long timestamp) {
Calendar givenDate = Calendar.getInstance();
givenDate.setTimeInMillis(timestamp);
givenDate.set(Calendar.HOUR_OF_DAY, 0);
givenDate.set(Calendar.MINUTE, 0);
givenDate.set(Calendar.SECOND, 0);
givenDate.set(Calendar.MILLISECOND, 0);
return givenDate.getTimeInMillis();
}
public static long getTimeStampAt0000ForTomorrow() {
long now = System.currentTimeMillis();
long nowAt0000 = getTimeStampAt0000(now);
if (now == nowAt0000) {
// if being queried at 00:00, we are assuming we want same or else we can just remove
// this condition
return nowAt0000;
} else {
return nowAt0000 + 86400000;
}
}
答案 1 :(得分:0)
SQLite doc表示它存储为:
INTEGER as Unix Time,自1970-01-01 00:00:00 UTC以来的秒数。
你某些你有epoch或几秒后的毫秒数吗?
捆绑的java.util.Date和Calendar类非常麻烦。避免他们。在Java 8中使用Joda-Time或新的java.time。*包。
请注意,java.util.Date和Joda-Time DateTime都使用自纪元以来的毫秒数,而新的java.time使用纳秒。根据需要乘以1000L
。
在谈论带有日期时间的“今天”和“明天”时,您必须指定一个时区。一天的开始和结束取决于time zone。
// Simulate input.
long millis = DateTime.now().getMillis();
// Use a proper time zone name rather than 3-letter codes.
DateTimeZone timeZone = DateTimeZone.forID( "Asia/Kolkata" ); // Formerly known as Calcutta, India.
DateTime dateTime = new DateTime( millis, timeZone );
DateTime aDayLater = dateTime.plusDays( 1 );
// "Tomorrow" is a span of time.
DateTime startOfToday = new DateTime( timeZone ).withTimeAtStartOfDay();
// Interval comparison is done in "half-open" approach where beginning is inclusive and ending is exclusive.
Interval tomorrow = new Interval( startOfToday.plusDays( 1 ), startOfToday.plusDays( 2 ) );
boolean isDateTimeOccurringTomorrow = tomorrow.contains( dateTime );
boolean isADayLaterOccurringTomorrow = tomorrow.contains( aDayLater );
转储到控制台...
System.out.println( "millis: " + millis );
System.out.println( "dateTime: " + dateTime );
System.out.println( "aDayLater: " + aDayLater );
System.out.println( "startOfToday: " + startOfToday );
System.out.println( "tomorrow: " + tomorrow );
System.out.println( "isDateTimeOccurringTomorrow: " + isDateTimeOccurringTomorrow );
System.out.println( "isADayLaterOccurringTomorrow: " + isADayLaterOccurringTomorrow );
跑步时......
millis: 1392883763016
dateTime: 2014-02-20T13:39:23.016+05:30
aDayLater: 2014-02-21T13:39:23.016+05:30
startOfToday: 2014-02-20T00:00:00.000+05:30
tomorrow: 2014-02-21T00:00:00.000+05:30/2014-02-22T00:00:00.000+05:30
isDateTimeOccurringTomorrow: false
isADayLaterOccurringTomorrow: true