Determine if a time is between two times regardless of date

前端 未结 3 1919
死守一世寂寞
死守一世寂寞 2021-01-29 10:06

I created a custom TimePicker preference for my Android Wear watch face. The user selects a time and it returns the current time in milliseconds. The code for this

3条回答
  •  面向向阳花
    2021-01-29 10:51

    Try implementing something like this method below. Might need some modifications.

    private boolean isTimeBetween(long startMillis, long endMillis, long testMillis) {
       long startHour = (startMillis / (1000 * 60 * 60)) % 24;
       long startMinute = (startMillis / (1000 * 60)) % 60;
       long startSecond = (startMillis / 1000) % 60;
       long endHour = (endMillis / (1000 * 60 * 60)) % 24;
       long endMinute = (endMillis / (1000 * 60)) % 60;
       long endSecond = (endMillis / 1000) % 60;
       long testHour = (testMillis / (1000 * 60 * 60)) % 24;
       long testMinute = (testMillis / (1000 * 60)) % 60;
       long testSecond = (testMillis / 1000) % 60;
    
       if (startHour < endHour) {
          if (testHour > startHour && testHour < endHour) {
             return true;
          } else if ((testHour == startHour && testMinute > startMinute) || (testHour == endHour && testMinute < endMinute)) {
             return true;
          } else if ((testHour == startHour && testMinute == startMinute && testSecond > startSecond) || (testHour == endHour && testMinute == endMinute && testSecond < endSecond)) {
             return true;
          } else {
             return false;
          }
       } else if (startHour > endHour) {
          if ((testHour > startHour && testHour <= 24) && (testHour < endHour && testHour >= 0)) {
             return true;
          } else if ((testHour == startHour && testMinute > startMinute || (testHour == endHour && testMinute < endMinute))) {
             return true;
          } else if ((testHour == startHour && testMinute == startMinute && testSecond > startSecond || (testHour == endHour && testMinute == endMinute && testSecond < endSecond))) {
             return true;
          } else {
             return false;
          }
       } else {
          if (testMinute > startMinute && testMinute < endMinute) {
             return true;
          } else if ((testMinute == startMinute && testSecond > startSecond) || (testMinute == endMinute && testSecond < endSecond)) {
             return true;
          } else {
             return false;
          }
       }
    }
    

    (Code not tested)

提交回复
热议问题