Search code examples
androiddatetimetextviewtimezoneinequality

Date inequality is not functioning in android


I want to display a text when time is between 20:45 and 23:15

    Time today = new Time(Time.getCurrentTimezone());
    today.setToNow();

if ((today.hour>=20 && today.minute>=45) 
               && (today.hour<=23 && today.minute<=15) ){
           MainTextView.setText("my text");}

The problem is that in this way the minutes interfere with each other (in fact it is impossible for it to be less than 15 and at the same time bigger than 45), so no text is displayed. Any ideas?


Solution

  • Yes, you just need to fix your logic. You only need to compare the minutes if the hour is a borderline hour. For example:

    if ((today.hour > 20 || (today.hour == 20 && today.minute >= 45)) &&
        (today.hour < 23 || (today.hour == 23 && today.minute <= 15)) {
      ...
    }
    

    Alternatively, convert the time into a "minutes of day" and do the arithmetic based on that:

    int minuteOfDay = today.hour * 60 + today.minute;
    if (minuteOfDay >= 20 * 60 + 45 &&
        minuteOfDay <= 23 * 60 + 15) {
      ...
    }