无论日期如何,确定时间是否介于两个其他时间

时间:2017-06-26 23:58:00

标签: java android datetime

我有以下代码

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_Hour8pm。它需要适用于这些情况:

1)如果Current_Hour介于6:00pm11:15pm

之间,则返回 true

2)如果Current_Hour介于6:00pm2:00am

之间,则返回 true

3)如果Current_Hour介于3:45pm6:10pm

之间,则返回 false

如果Current_Hour2am,则需要满足以下条件:

4)如果Current_Hour介于1:00am3:30am

之间,则返回 true

5)如果Current_Hour介于7:00am12:02pm

之间,则返回 false

我整天都在努力,无论我做什么,我都可以满足上述要求中的一两个。

无论日期如何,这都需要工作 - 尽管情况#2需要它。

任何帮助将不胜感激。我疯了。

1 个答案:

答案 0 :(得分:2)

如果您想比较时间与分钟的精确度,请从每个分钟中获取每日分钟值,即minuteOfDay = hourOfDay * 60 + minuteOfHour,然后进行比较。

您可以根据需要将其扩展到秒或毫秒。

由于您希望6:00pm2: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);
}