Test date at least one day earlier

Asked

Viewed 650 times

2

System that controls Orders of Service, the moment I open a new service order I close the previous order. If the previous service order was opened on an earlier date (at least one day ago) I close it at the end of the previous day’s working hours and open the new one at the beginning of the current day’s working hours.

What I’m wanting with this, a way to find out if the date in question is at least a day earlier. I thought about testing the time difference between the end of the previous day’s working hours and the beginning of the current day’s working hours, but it doesn’t seem like a good solution.

I did a test with Legend as follows:

Calendar diaAnterior = DATA_HORA_INICIAL_OS;
diaAnterior.add(Calendar.DATE, 1);
  if (DATA_HORA_ATUAL.get(Calendar.DATE) >= diaAnterior.get(Calendar.DATE)) {
    return true;
  }
return false;

However this way it just tests the day in question and if it has been opened the day 30 of the month and today is day 1, the method will return me invalid information, or if I have gone on vacation and come back at the beginning of the month, the same error would happen.

So how can I test whether the date of the opening of the work order is at least the previous day?

  • Taking the opportunity, I leave you a recommendation to use the new date API, which is more efficient.

  • Poh! Thanks man, I really had no knowledge of this API, I’ll take a look. Problem for me that Java 8 no longer accepts Windows XP.

1 answer

3


By zeroing out the hours attributes, you will have exactly midnight tonight. With this, you can check if the date of the parameter is earlier than today.

public static void main(String[] args) {
    Calendar dataOrdem = Calendar.getInstance();
    // coloca a data em 31/03
    dataOrdem.set(Calendar.DAY_OF_MONTH, 31);
    dataOrdem.set(Calendar.MONTH, 2); // 2 = março

    System.out.println(testarDiaAnterior(dataOrdem));

  }

  private static boolean testarDiaAnterior(Calendar dataOrdem){
    Calendar hoje = Calendar.getInstance();
    hoje.set(Calendar.HOUR, 0);
    hoje.set(Calendar.MINUTE, 0);
    hoje.set(Calendar.SECOND, 0);
    hoje.set(Calendar.MILLISECOND, 0);
    return hoje.after(dataOrdem);
  }

Note: You can also use the before method:

return dataOrdem.before(hoje);

But, because it is a parameter, at some point the method may receive null.

  • Hello, could you explain the code?

  • zero the attributes of hours you will have exactly at midnight tonight. With this, if today at midnight is after the date passed by parameter, it means that the date is earlier.

  • Jefferson puts in the answer, it’s easier. Click the button editar to edit the answer. Take advantage and make a tour to learn more about the site.

  • @cat changed response. Thanks for the tip.

  • It makes a lot of sense, thank you

Browser other questions tagged

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