0

I store a number of rows in DB with the timestamp of that moment in milliseconds. Now if I need to retrieve all rows of a given day, like today, how do I correctly create the starting and ending milliseconds of that day?

I know about SimpleDateFormat and Calendar.getInstance() briefly, but would I need to do string manipulation (which I want to avoid) to get todays date only, add the hours part and then convert it back into milliseconds, or is there a better way to do it?

4

4 回答 4

1

Since you didn't provide any code in your question, please allow me to give you a general answer in response..

What you're looking for are two date/times, today and tomorrow, both specified a "0 hours, 0 minutes, 0 seconds".

today <= date AND date < tomorrow

Note the two different comparisons.

于 2013-08-11T05:45:56.260 回答
0

您可以使用 GregorianCalendar 类在没有任何字符串的情况下执行此操作。

    Calendar calendar = new GregorianCalendar(year, month, day);
    long start_of_day_millis = calendar.getTimeInMillis();
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    长 next_day_millis = calendar.getTimeInMillis();

使用calendar.add(Calendar.DAY_OF_MONTH);而不是仅仅将 (24*60*60*1000) 添加到第一个毫秒值的原因是为了考虑跳跃。除了众所周知的闰年之外,还会出现闰秒。请参阅此链接:http ://www.timeanddate.com/time/leapseconds.html

确保您的表达式包含start_of_day_millis(大于或等于)且不包含next_day_millis(小于)。
IE:if(test_time >= start_of_day_millis && test_time < next_day_millis)

更新:如果您想要今天的日期,
您可以省略日历构造函数中的所有参数,只需new GregorianCalendar()调用calendar.set(Calendar._FIELD_NAME_, 0);日历,因为它将被初始化到创建对象的确切时刻。

于 2013-08-10T16:36:41.527 回答
0

最简单的技术是使用DateFormat

String input = "Sat Feb 17 2013";
Date date = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long milliseconds = date.getTime();
String input1="Sun Feb 18 2013"
Date inputNextDay = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long millisecondsForNextDay=inputNextDay.getTime();

要获取特定日期的行,只需找到时间戳的毫秒值介于milliseconds和之间的行millisecondsForNextDay

if(rowsTimestampSeconds>milliseconds && rowsTimestampSeconds<millisecondsForNextDay){
    //get the row
}
于 2013-08-10T16:19:54.067 回答
0
于 2016-05-03T23:06:23.540 回答