0

如果当前时间是 18,则此逻辑不起作用。这里开始时间是 22(晚上 10 点),结束时间是 06(早上 6 点)提前谢谢。

int hour = currentTime.get(Calendar.HOUR_OF_DAY);

if (hour > 22) {
        if (hour > 06) {
            return true;

        }
    }

    if (hour < 22) {
        if (hour < 06) {
            return true;
        }
    }

    if (hour == 00) {
        return true;
    }
    return false;
4

1 回答 1

1

Your logic is far to localized to a specific case, but you need:

if (endHour < startHour) { // the end is on the next day
    if (hour > startHour || hour < endHour) {
        return HOUR_IS_IN_RANGE;
    }
}
else { // end hour is on the same day as start shour
    if (hour >startHour && hour < endHour) {
        return HOUR_IS_IN_RANGE;
    }
 }
 return HOUR_NOT_IN_RANGE;

You should also consider >=/<= instead of just > and <.

于 2012-10-09T06:26:14.263 回答