我有以下Holiday
类(class):
public class Holiday {
private int day;
private int month;
public Holiday(GregorianCalendar calendar) {
this.day = calendar.get(GregorianCalendar.DAY_OF_MONTH);
this.month = calendar.get(GregorianCalendar.MONTH) + 1;
}
}
枚举日:
public enum Day {
SATURDAY(6), SUNDAY(7);
private int index;
Day(int index) {
this.index = index;
}
public int getIndex() {
return index;
}
}
public class DateTool {
private static final String DATE_FORMAT = "yyyy_MM_dd";
public DateTool() {
super();
}
public static String getPreviousWorkingDay(List<Holiday> listOfHolidays) {
//derive the last working day that is not saturday/sunday
}
public static String parseDate(Date date) {
return new SimpleDateFormat(DATE_FORMAT).format(date);
}
public static boolean isSunday(LocalDateTime date) {
return date.getDayOfWeek().getValue() == Day.SUNDAY.getIndex();
}
public static boolean isSaturday(LocalDateTime date) {
return date.getDayOfWeek().getValue() == Day.SATURDAY.getIndex();
}
}
鉴于我有假期
的列表
,我如何计算并在getPreviousWorkingDay(...)
中返回前一个工作日排除星期六和星期日的方法?
我正在尝试导出要查找的最后一个文件日期,因此我正在尝试解决这样的问题
if (todayIsHoliday(listOfHolidays)) {
getPreviousWorkingDay(listOfHolidays);
}
所以如果当天是假期,请查看最后一个不是假期的日期并以字符串格式返回。
我不确定如何回顾。请注意,假期列表不仅包括周六和周日。它们是乡村假期,例如农历新年等。
我为此使用的是 java 8,因此欢迎任何重构或改进:)
最佳答案
private static final DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("uuuu_MM_dd");
public static String getPreviousWorkingDay(List<MonthDay> listOfHolidays) {
LocalDate workingDay = LocalDate.now(ZoneId.of("Pacific/Easter")).minusDays(1);
while (workingDay.getDayOfWeek().equals(DayOfWeek.SATURDAY)
|| workingDay.getDayOfWeek().equals(DayOfWeek.SUNDAY)
|| listOfHolidays.contains(MonthDay.from(workingDay))) {
workingDay = workingDay.minusDays(1);
}
return workingDay.format(dateFormatter);
}
我正在使用 java.time
,现代 Java 日期和时间 API,正如评论中提到的,我建议您也这样做。让我们看看上面的方法的实际效果:
System.out.println(getPreviousWorkingDay(Collections.emptyList()));
// Let’s say Valentin’s day is a holiday
System.out.println(getPreviousWorkingDay(List.of(MonthDay.of(Month.FEBRUARY, 14))));
// And so are Lent Monday and the death day of Danish would-be king Henrik
System.out.println(getPreviousWorkingDay(List.of(MonthDay.of(Month.FEBRUARY, 12),
MonthDay.of(Month.FEBRUARY, 13), MonthDay.of(Month.FEBRUARY, 14))));
今天打印了:
2018_02_14
2018_02_13
2018_02_09
(我有点作弊,因为四旬斋星期一不是每年的同一天;但我认为不需要考虑这些假期。)
由于确定今天的日期是一个时区敏感操作,如果不是复活节岛时区,请替换您所需的时区。编辑:在 Java 8 中使用 Arrays.asList() 而不是 Java 9 List.of()。
链接: Oracle tutorial: Date Time解释如何使用java.time
。
关于java - 最后一个工作日期非假期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48808021/