The code below helps you find the number of a specified weekday (Monday, Tuesday, Wednesday, etc.) between two dates. The solution we used below is to loop between the two dates and check if the weekday of those dates are equals to the day we want to count.
package org.kodejava.util;
import java.util.Calendar;
public class DaysBetweenDate {
public static void main(String[] args) {
Calendar start = Calendar.getInstance();
start.set(2021, Calendar.OCTOBER, 1);
Calendar end = Calendar.getInstance();
end.set(2021, Calendar.OCTOBER, 31);
System.out.print("Number Monday between " +
start.getTime() + " and " + end.getTime() + " are: ");
int numberOfDays = 0;
while (start.before(end)) {
if (start.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY) {
numberOfDays++;
start.add(Calendar.DATE, 7);
} else {
start.add(Calendar.DATE, 1);
}
}
System.out.println(numberOfDays);
}
}
The result of our program is:
Number Monday between Fri Oct 01 07:55:06 CST 2021 and Sun Oct 31 07:55:06 CST 2021 are: 4
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024