我有以下代码
private boolean checkIfTimeInBetweenRegardlessOfDate(long timeOne, long timeTwo) {
final Calendar firstCalendar = Calendar.getInstance();
firstCalendar.setTimeInMillis(timeOne);
final Calendar calendarCurrentTime = mCalendar;
final Calendar secondCalendar = Calendar.getInstance();
secondCalendar.setTimeInMillis(timeTwo);
final Calendar calendarOneToCompare = Calendar.getInstance();
calendarOneToCompare.setTimeInMillis(calendarCurrentTime.getTimeInMillis());
calendarOneToCompare.set(Calendar.HOUR_OF_DAY, firstCalendar.get(Calendar.HOUR_OF_DAY));
calendarOneToCompare.set(Calendar.MINUTE, firstCalendar.get(Calendar.MINUTE));
final Calendar calendarTwoToCompare = Calendar.getInstance();
calendarTwoToCompare.setTimeInMillis(calendarCurrentTime.getTimeInMillis());
calendarTwoToCompare.set(Calendar.HOUR_OF_DAY, secondCalendar.get(Calendar.HOUR_OF_DAY));
calendarTwoToCompare.set(Calendar.MINUTE, secondCalendar.get(Calendar.MINUTE));
if ((calendarTwoToCompare.getTime().toString())
.compareTo(calendarOneToCompare.getTime().toString()) < 0) {
calendarTwoToCompare.add(Calendar.DATE, 1);
calendarCurrentTime.add(Calendar.DATE, 1);
}
return (calendarOneToCompare.compareTo(calendarCurrentTime) <= 0
&& calendarCurrentTime.compareTo(calendarTwoToCompare) <= 0);
}
所以这个问题在SO之前已经出现了几次。没有人的代码似乎适用于所有情况。
假设Current_Hour
为8pm
。它需要适用于这些情况:
1)如果Current_Hour
介于6:00pm
和11:15pm
2)如果Current_Hour
介于6:00pm
和2:00am
3)如果Current_Hour
介于3:45pm
和6:10pm
如果Current_Hour
为2am
,则需要满足以下条件:
4)如果Current_Hour
介于1:00am
和3:30am
5)如果Current_Hour
介于7:00am
和12:02pm
我整天都在努力,无论我做什么,我都可以满足上述要求中的一两个。
无论日期如何,这都需要工作 - 尽管情况#2需要它。
任何帮助将不胜感激。我疯了。
答案 0 :(得分:2)
如果您想比较时间与分钟的精确度,请从每个分钟中获取每日分钟值,即minuteOfDay = hourOfDay * 60 + minuteOfHour
,然后进行比较。
您可以根据需要将其扩展到秒或毫秒。
由于您希望6:00pm
和2:00am
覆盖8pm
,因此您需要检测反转的时间范围。
总而言之,你可以这样做:
private static boolean isTimeInRange(long currentMillis, long fromMillis, long toMillis) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(currentMillis);
int currentMinuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
cal.setTimeInMillis(fromMillis);
int fromMinuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
cal.setTimeInMillis(toMillis);
int toMinuteOfDay = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
if (fromMinuteOfDay <= toMinuteOfDay)
return (currentMinuteOfDay >= fromMinuteOfDay && currentMinuteOfDay < toMinuteOfDay);
return (currentMinuteOfDay >= fromMinuteOfDay || currentMinuteOfDay < toMinuteOfDay);
}