基本上我需要从数据库中获取一个动态字符串数组(将从数据库中填充,但在此示例中它只是一个固定大小用于测试),将其转换为Calendar数组,以便我可以将其与当天迭代,看它是否等于星期六/星期日或新创建的日历数组中的任何日子。
我的问题是日历数组没有正确填充,因为当while循环将当前日期与假期设置进行比较时,它不会被考虑在内吗?
到目前为止,这是我的代码;
private static final String[] bankHolidays = {"25/03/2016","28/03/16","02/05/2016","20/05/2016"};
private static Set<Calendar> holidayDates;
static SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
public static void main(String[] args) throws ParseException {
if(holidayDates == null) {
holidayDates = new HashSet<Calendar>();
Date[] hol = new Date[bankHolidays.length];
for(int i=0;i<bankHolidays.length;i++){
Date d = sdf.parse(bankHolidays[i]);
hol[i]= d;
}
for(Date day : hol) {
Calendar c = Calendar.getInstance();
c.setTime(day);
holidayDates.add(c);
}
}
在比较阶段,代码是;
if (startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY && startCal.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY && !holidayDates.contains(startCal.get(Calendar.DAY_OF_YEAR)) ) {
++workDays;
}
有什么建议吗?
编辑:我最终想到这一点,但其中一个因素是使用MM代替mm来比较日期。答案 0 :(得分:1)
您的代码示例的修复,更清晰的版本:)(使用您的JDK5语言级别。可以通过Java 8流API进一步改进)
private static final String[] bankHolidays = {"25/03/2016", "28/03/16", "02/05/2016", "20/05/2016"};
private static final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
private static Set<Calendar> holidayDates;
public static void main(String[] args) throws ParseException {
if (holidayDates == null) {
holidayDates = new HashSet<Calendar>();
for (int i = 0; i < bankHolidays.length; i++) {
Calendar c = Calendar.getInstance();
Date date = sdf.parse(bankHolidays[i]);
c.setTime(date);
holidayDates.add(c);
}
}
}