You can parse the input dates into LocalDate
and the create a loop from the start date to the end date with a step of one day. Inside the loop, add the dates, which do not fall on Sun or Sat, to a list.
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("First date: ");
String strDate1 = input.nextLine();
System.out.print("Second date: ");
String strDate2 = input.nextLine();
LocalDate date1 = LocalDate.parse(strDate1);
LocalDate date2 = LocalDate.parse(strDate2);
List<LocalDate> listBusinessDates = new ArrayList<>();
for (LocalDate date = date1; !date.isAfter(date2); date = date.plusDays(1)) {
DayOfWeek dayOfWeek = date.getDayOfWeek();
if (!(dayOfWeek.equals(DayOfWeek.SATURDAY) || dayOfWeek.equals(DayOfWeek.SUNDAY))) {
listBusinessDates.add(date);
}
}
System.out.println(listBusinessDates);
}
}
A sample run:
First date: 2020-11-23
Second date: 2020-12-13
[2020-11-23, 2020-11-24, 2020-11-25, 2020-11-26, 2020-11-27, 2020-11-30, 2020-12-01, 2020-12-02, 2020-12-03, 2020-12-04, 2020-12-07, 2020-12-08, 2020-12-09, 2020-12-10, 2020-12-11]
Note that the date-time API of java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.
Note: For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.