Java Get All Working Days in a year in YYYYMMDD format
Since it's 2020, you really should be embracing the java.time.*
API.
While I'm sure there's probably a really neat way to get the "working" days between to dates, I've gone for the brute force method...
LocalDate ld = LocalDate.of(2020, Month.JANUARY, 1);
LocalDate endDate = ld.plusYears(1);
// You don't "have" to put into a list, but I like to seperate my
// code responsbilities ;)
List<LocalDate> workDays = new ArrayList<>(365);
System.out.println(endDate);
while (ld.isBefore(endDate)) {
// This would be a good place for a delegate to determine if we want the specific day
// as it could then take into account public holidays
if (ld.getDayOfWeek() == DayOfWeek.SATURDAY || ld.getDayOfWeek() == DayOfWeek.SUNDAY) {
// NOOP
} else {
workDays.add(ld);
}
ld = ld.plusDays(1);
}
Then you can simply use a DateTimeFormatter
to format the LocalDate
into a format that you want, for example...
DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyyMMdd");
List<String> formats = workDays.stream().map(value -> value.format(format)).collect(Collectors.toList());
for (String value : formats) {
System.out.println(value);
}
Set<DayOfWeek> weekend = EnumSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY);
LocalDate.of(2019, Month.JANUARY, 1)
.datesUntil(LocalDate.of(2020, Month.DECEMBER, 31), Period.ofDays(1))
.filter(x -> !weekend.contains(x.getDayOfWeek()))
.forEachOrdered(System.out::println);
A lucid way to display all weekdays in a date range using Java 8 and modern date-time API is as follows:
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
List<LocalDate> dates = getDates("2019-01-01", "2019-12-31");
for (LocalDate date : dates) {
System.out.println(DateTimeFormatter.BASIC_ISO_DATE.format(date));
}
}
public static List<LocalDate> getDates(String fromDate, String toDate) {
LocalDate startDate = LocalDate.parse(fromDate);
LocalDate endDate = LocalDate.parse(toDate).plusDays(1);
long range = ChronoUnit.DAYS.between(startDate, endDate);
return Stream.iterate(startDate, date -> date.plusDays(1)).limit(range)
.filter(d -> !(d.getDayOfWeek() == DayOfWeek.SATURDAY || d.getDayOfWeek() == DayOfWeek.SUNDAY))
.collect(Collectors.toList());
}
}
Output:
20190101
20190102
20190103
20190104
20190107
20190108
...
...
...
20191226
20191227
20191230
20191231