如何使用java.util.Calendar在每年的同一日期设置定期假期(忽略年份部分)?



我正在制作一个日历,允许您添加每年自动重复的特定假期。 我的工作日日历.class需要 2 种方法: -setHoliday(日历日期(,仅设置该年内的假期 -setRecurringHoliday(日历日期(,它应该(最好(使用setHoliday((并将其设置为每年重复出现。 如何实现检查是否为新年的逻辑?我正在将假期添加到名为假期列表的哈希集中。我需要一种方法来检查它是否是新的一年,然后添加一个指定的假期。 setHoliday工作正常,并且已经过单元测试测试。

public void setHoliday(Calendar date) {
this.date = date.getTime();
if (!isHoliday(date)) {
holidaysList.add(this.date);
}
}
public void setRecurringHoliday(Calendar date) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy HH:mm");
GregorianCalendar todaysDate = new GregorianCalendar();
System.out.println(
sdf.format("Todays date: " + todaysDate.getTime()) + "n");
int thisYear = todaysDate.get(Calendar.YEAR);
int chosenYear = date.get(Calendar.YEAR);
System.out.println("Chosen year: " + chosenYear + "nThis year: " + thisYear);
date.add(Calendar.YEAR, 1);
int nextYear = date.get(Calendar.YEAR);
System.out.println("Next year: " + nextYear);

/*What to do here???*/
if (thisYear == nextYear){
setHoliday(date);
System.out.println("recurring holiday added");
}
}
private boolean isHoliday(Calendar date) {
this.date = date.getTime();
return isWeekend(date) || holidaysList.contains(this.date);
}
private boolean isWeekend(Calendar date) {
int chosenDay = date.get(Calendar.DAY_OF_WEEK);
return chosenDay == Calendar.SATURDAY || chosenDay == Calendar.SUNDAY;
}

您正在使用糟糕的日期时间类,这些类几年前被JSR 310中定义的java.time类所取代。

MonthDay

对于没有年份的月份和日期,请使用MonthDay

MonthDay xmas = MonthDay.of( Month.DECEMBER , 25 ) ;

你的假期应该是一组MonthDay对象,从我能辨别出你的问题。我发现您的整体问题令人困惑,因为它的逻辑无法满足您通常工作场所假期跟踪的需求。

Set< MonthDay > holidays = new TreeSet<>() ;
holidays.add( xmas ) ;

对于日期,请使用LocalDate

申请一年以获得日期。

LocalDate xmas2020 = xmas.atYear( 2020 ) ;

若要获取当前年份,请使用Year,并指定时区。对于任何给定的时刻,日期,因此可能是年份,在全球范围内因地区而异。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
Year currentYear = Year.now( z ) ;
LocalDate xmasThisYear = currentYear.atMonthDay( xmas ) ;

添加到明年的Year

Year nextYear = currentYear.plusYears( 1 ) ;
LocalDate xmasNextYear = nextYear.atMonthDay( xmas ) ;

询问日期是今年还是明年。

boolean isThisYear = Year.from( localDate ).equals( currentYear ) ;
boolean isNextYear = Year.from( localDate ).equals( nextYear ) ;
boolean isFutureYear = Year.from( localDate ).isAfter( currentYear ) ;

要检查周末,请定义DayOfWeek枚举中定义的所需星期几值的EnumSet

Set< DayOfWeek > weekend = EnumSet.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;
boolean isWeekend = weekend.contains( localDate.getDayOfWeek() ) ;

最新更新