-3

I'm trying to get the range of time from 8:00 am to 8:00 pm and 8:00 pm to 8:00 am, I'm trying to get schedules to display it in the recyclerview from firebase.

This is the code that I've structured.

 Calendar c = Calendar.getInstance();
    hour = c.get(Calendar.HOUR_OF_DAY);
    min = c.get(Calendar.MINUTE);
    sec = c.get(Calendar.SECOND);
    int ds = c.get(Calendar.AM_PM);
    if(ds==0)
        AM_PM="am";
    else
        AM_PM="pm";

    Toast.makeText(getActivity(), ""+hour+":"+min+AM_PM, Toast.LENGTH_SHORT).show();

    if (hour >= 8 && AM_PM.matches("am") || hour >= 12 && AM_PM.matches("pm") || hour <= 7 && min <=59 && sec <=59  && AM_PM.matches("pm") ){
        fill_with_data_shift1();
    }else if (hour >= 20 && AM_PM.matches("pm") || hour >= 00 && AM_PM.matches("am")){
        fill_with_data_shift2();
    }

2 Answers2

2

Using the modern Java date & time API this comes quite naturally:

    LocalTime currentTime = LocalTime.now(ZoneId.of("Asia/Manila"));

    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("h:mma", Locale.ENGLISH);
    String displayTime = currentTime.format(dtf).toLowerCase();
    Toast.makeText(getActivity(), displayTime, Toast.LENGTH_SHORT).show();

    if (currentTime.isBefore(LocalTime.of(8, 0))
            || ! currentTime.isBefore(LocalTime.of(20, 0))) { // not-before means on or after
        fill_with_data_shift2();
    } else {
        fill_with_data_shift1();
    }

Since getting the local time is a time zone sensitive operation, think twice about the time zone you pass to LocalTime.now(). If you want to use the device’s time zone setting, pass ZoneId.systemDefault().

For Android you get the modern API in ThreeTenABP, see this question: How to use ThreeTenABP in Android Project.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
1

Basically your code should be:

// between 8am and 8pm (not included)
if (hour >= 8 && hour < 20) {
    // Do something
} else { // the rest of the time
    // Do something else
}

Minutes, seconds and all the rest don't matter.

Eselfar
  • 3,759
  • 3
  • 23
  • 43