Business Days Between Two Dates
Problem
Two dates are given in the form YYYY-MM-DD (the first is not later than the second). Count how many days from the first date (included) to the second date (not included) are Monday to Friday. Holidays are ignored.
Constraints
- dates between 1970-01-01 and 2100-12-31
Examples
Input
2026-10-19 2026-10-26
Output
5
Solutions
A loop visits every day and counts Monday to Friday. It is the clearest version, and the cost is the number of days between the two dates.
/*
* Problem : Count weekdays.
* Input : Two dates.
* Output : Number of weekdays.
* Approach: Walk day by day.
* Time : O(days)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// This method solves the task. It receives the input and returns the answer.
static long solve(String a, String b) {
// Step 1: Walk from the first date to the day before the second date and count the weekdays.
java.time.LocalDate day = java.time.LocalDate.parse(a);
java.time.LocalDate end = java.time.LocalDate.parse(b);
long count = 0;
while (day.isBefore(end)) {
java.time.DayOfWeek weekday = day.getDayOfWeek();
if (weekday != java.time.DayOfWeek.SATURDAY && weekday != java.time.DayOfWeek.SUNDAY) {
count++;
}
day = day.plusDays(1);
}
return count;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String a = scanner.next();
String b = scanner.next();
System.out.println(solve(a, b));
}
}
Hints (2)
- Is the end date counted?
- Which day numbers mean Saturday and Sunday?