Compare android time slot

Asked

Viewed 57 times

0

I have a register where the establishment puts its opening hours in variables String, Ex: horario_abertura and horario_fechamento format: 00:00 24hrs.

I need the application to compare the current time with the opening and closing of the establishment, to inform if it is open or closed!

Does anyone have an example?

1 answer

1


You can do it like this:

public static final String inputFormat = "HH:mm";

private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;

private String horarioabertura = "8:45";
private String horariofechamento = "18:45";

SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);

private void compareDates(){
    Calendar now = Calendar.getInstance();

    int hour = now.get(Calendar.HOUR_OF_DAY);
    int minute = now.get(Calendar.MINUTE);

    date = parseDate(hour + ":" + minute);
    dateCompareOne = parseDate(horarioabertura);
    dateCompareTwo = parseDate(horariofechamento);

    if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
        //esta aberto
    } else
        //esta fechado
}

private Date parseDate(String date) {

    try {
        return inputParser.parse(date);
    } catch (java.text.ParseException e) {
        return new Date(0);
    }
}
  • Thanks for the reply, is comparing but only in 12hrs format. When the time exceeds noon it is always closed.

  • Actually when it passes half a day does not enter the if

  • I edited the answer.

  • Thank you! It worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.