When writing business logic, you may need a date n business days later. (Alert, etc. if processing is not performed within n business days) However, it is quite troublesome to ask for this. It is easy to calculate if the holidays are only Saturdays and Sundays, but there is no fixed rule for holidays. You need to create and manage a master on your system or obtain information from the outside.
The former is troublesome because you have to manage the master yourself, so this time I created a class to check the business days by the latter means.
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class BusinessDayApiAccessorServiceImpl implements BusinessDayApiAccessor {
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("uuuuMMdd");
private final OkHttpClient client;
@Override
public LocalDate getBusinessDayAfter(LocalDate baseDate, int days) {
return getBusinessDay(true, baseDate, days);
}
@Override
public LocalDate getBusinessDayBefore(LocalDate baseDate, int days) {
return getBusinessDay(false, baseDate, days);
}
private LocalDate getBusinessDay(boolean isNext, LocalDate baseDate, int days) {
if (days == 0) {
return baseDate;
}
return getBusinessDay(isNext, sendRequest(isNext, isNext ? baseDate.plusDays(1) : baseDate.minusDays(1)),
days - 1);
}
private LocalDate sendRequest(boolean isNext, LocalDate baseDate) {
HttpUrl httpUrl = new HttpUrl.Builder().scheme("http").host("s-proj.com").addPathSegment("utils")
.addPathSegment("getBusinessDay.php").addQueryParameter("kind", isNext ? "next" : "prev")
.addQueryParameter("date", baseDate.format(DATE_FORMATTER)).build();
Request request = new Request.Builder().url(httpUrl).get().build();
try (Response response = client.newCall(request).execute()) {
String resultBody = response.body().string();
return LocalDate.parse(resultBody, DATE_FORMATTER);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean isBusinessDay(LocalDate date) {
return sendRequest(true, date).isEqual(date);
}
}
Public Holiday Check will use the public holiday API of the public as a source for determining business days. This API will return the date if the target date is a business day, and the next or previous business day if it is not a business day. Therefore, you can find the date n business days later (or before) by executing the method of hitting the API while shifting the date by one day until it reaches n. In addition, OkHttp is used to hit the API.
Since API access to the outside is sandwiched and recursive logic, it is realistic that the value of n is at most around 10. If you try to ask for something like 100 business days later, it will be difficult. (I don't think there is much in business) If you need it, it is safer to use another method.
Recommended Posts