pointing to previous working day using java

前端 未结 4 1161
北恋
北恋 2020-12-18 03:43

I am new with using java.calendar.api. I want to point to the previous working day for a given day using java. BUT the conditions goes on increasing when i am using calend

4条回答
  •  失恋的感觉
    2020-12-18 04:04

    While you should consider using the Joda Time library, here's a start with the Java Calendar API:

    public Date getPreviousWorkingDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
    
        int dayOfWeek;
        do {
            cal.add(Calendar.DAY_OF_MONTH, -1);
            dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
        } while (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY);
    
        return cal.getTime();
    }
    

    This only considers weekends. You'll have to add additional checks to handle days you consider holidays. For instance you could add || isHoliday(cal) to the while condition. Then implement that method, something like:

    public boolean isHoliday(Calendar cal) {
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
    
        if (month == 12 && dayOfMonth == 25) {
            return true;
        }
    
        // more checks
    
        return false;
    }
    

提交回复
热议问题