The opening and closing hours for the company are 8am to 10 pm. The code below seems to add 4 hours on to whatever time is entered into the text field. So if I change the opening time to 11:59 I get the correct 8 am start date, but it's not possible to change the end time to 26:01 so I can't get the end time to work correctly. The data has to be stored in the database in UTC, but for display purposes it's displayed in EST.
public static boolean insideBusinessHours(String startTime, String endTime, String date) {
LocalDateTime localStart = stringToLDT_UTC(startTime, date);
LocalDateTime localEnd = stringToLDT_UTC(endTime, date);
String UTCstart = localStart.toString().substring(11,16);
String UTCend = localEnd.toString().substring(11,16);
LocalTime enteredStart = LocalTime.parse(UTCstart);
LocalTime enteredEnd = LocalTime.parse(UTCend);
LocalTime openingHour = LocalTime.of(07, 59);
LocalTime closingHour = LocalTime.of(22, 1);
Boolean startTimeAllowed = enteredStart.isAfter(openingHour);
Boolean endTimeAllowed = enteredEnd.isBefore(closingHour);
if (startTimeAllowed && endTimeAllowed) {
return true;
}
else {
return false;
}
}
public static LocalDateTime stringToLDT_UTC(String time, String date) {
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime ldt = LocalDateTime.parse(date + " " + time, format)
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(ZoneId.of("UTC"))
.toLocalDateTime();
return ldt;
}
Even though dates and times need to be stored in UTC, I believe that it makes more sense to do the comparisons in your local time.
Further comments:
07for the hour of the day looks nice. but you will get a surprise when08does not work. And in a different context, your users could get a pretty unpleasant surprise when for example0700does work but denotes 448.Booleanobjects. Don’t ever if you can avoid it since the risk of anullreference to aBooleanis confusing and from experience often leads to errors. Use primitiveboolean(lower caseb).return startTimeAllowed && endTimeAllowed;as terser than yourif-elsestatement.Link