JAVA - 如何制作自定义假期并跟踪它们

时间:2018-05-01 06:07:45

标签: java calendar

制作允许您添加特定假期的日历

2 个答案:

答案 0 :(得分:2)

您应该使用java.time包。特别是代表假期的MonthDay类,因为假期通常是固定的月份+天(但如果假期是“动态的”,你需要比Set<MonthDay>更复杂的逻辑。)

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.MonthDay;
import java.util.HashSet;
import java.util.Set;

public class CustomHolidays {
    private final Set<MonthDay> holidays = new HashSet<>();

    public void addHoliday(final MonthDay monthDay) {
        holidays.add(monthDay);
    }

    public boolean isHoliday(final LocalDate localDate) {
        return isWeekend(localDate) || holidays.contains(toMonthDay(localDate));
    }

    public int numberOfWorkdaysBetween(final LocalDate startInclusive, final LocalDate endInclusive) {
        int c = 0;
        for (LocalDate i = startInclusive; !i.isAfter(endInclusive); i = i.plusDays(1)) {
            if (!isHoliday(i)) {
                c++;
            }
        }
        return c;
    }

    private boolean isWeekend(final LocalDate localDate) {
        final DayOfWeek dow = localDate.getDayOfWeek();
        return dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY;
    }

    private static MonthDay toMonthDay(final LocalDate localDate) {
        return MonthDay.of(localDate.getMonth(), localDate.getDayOfMonth());
    }

    public static void main(String[] args) {
        final CustomHolidays ch = new CustomHolidays();
        ch.addHoliday(MonthDay.of(Month.MAY, 1));
        ch.addHoliday(MonthDay.of(Month.MAY, 2));
        ch.addHoliday(MonthDay.of(Month.MAY, 3));

        System.out.println(ch.numberOfWorkdaysBetween(LocalDate.of(2018, 5, 1), LocalDate.of(2018, 5, 8)));
    }
}

输出:3

答案 1 :(得分:1)

根据他人的建议,您应该继续使用java.time.LocalDate代替。

但如果您仍然对目前的方法无效的原因感到好奇,请提前阅读。

第一个问题:以下条件会在一天相等时停止,即使月份不同(因为dayIndex!= yDay会评估为false

while (monthIndex != yMonth && dayIndex != yDay)

将while条件更改为低于1将检查日期和月份。同时将monthIndexyMonth-1进行比较,因为您的monthIndex初始化为xMonth-1

while (!(monthIndex == yMonth-1 && dayIndex == yDay)) 

第二个问题:int calMonth = xMonth;更改为int calMonth = xMonth-1;出于与问题1中提到的相同的原因。

第3个问题:dayIndex初始化为0而不是1,因为您在dayIndex阻止后递增if 。如果您将其初始化为1,则会增加到2,因此会跳过每月的第1个日期。

        if (dayIndex == numDaysInMonth+1) {
            dayIndex = 0;
            monthIndex++;
        }
        dayIndex++;

检查here是否有工作小提琴