Checking dates if it is in a range

  • A+

My Java FX app handles hours worked. I have work start and end time in 2 date fields. I succeeded in calculating the differences between 2 datesTime; but now how could I check if the result is in a night or day range???? The day begin at 6 and ends at 22h. For example someone who worked between 3Am till 11Pm. Here is below how I did to have the total number of hours worked.

public void CalculNbreJourTravaille() {     SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyy HH:mm");      try {         Date ddtt = format.parse(ddt.getText());         Date dftt = format.parse(dft.getText());         long diff = dftt.getTime() - ddtt.getTime();         long diffhours = diff / (60*60*1000)%24;         long diffdays = diff/(24*60*60*1000);         long total = diffhours + (diffdays*24);         result.setText(total + " Hours");        } catch (ParseException e) {         // TODO Auto-generated catch block         e.printStackTrace();     } } 

We have workers who can work beyond 10PM, and the pay would not be the same. If they work after 10pm, they will have a special pay. We pay at the end of the work. They could would work only 10 days or more.

You should use the new DateTimeFormatter class to give you a LocalDateTime object, which you can pull the hour from.

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"); LocalDateTime localDateTimeFrom = format.parse(dateFrom.getText(), LocalDateTime::from); LocalDateTime localDateTimeTo = format.parse(dateTo.getText(), LocalDateTime::from);  int hoursFrom = localDateTimeFrom.getHour(); int hoursTo = localDateTimeTo.getHour();  boolean workedNight = hoursFrom < 6 || hoursTo > 22; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: