Java Calendar Day getWorkingDay(Calendar d1, Calendar d2)

Here you can find the source of getWorkingDay(Calendar d1, Calendar d2)

Description

get Working Day

License

Open Source License

Declaration

public static int getWorkingDay(Calendar d1, Calendar d2) 

Method Source Code

//package com.java2s;

import java.util.Calendar;

public class Main {
    /**//w w  w.  j av a2s.c  o  m
     * caculate the working days int "month"
     *
     * @param year
     * @param month
     * @return
     */
    public static int getWorkingDay(String year, String month) {
        Calendar cal_start = Calendar.getInstance();
        cal_start.set(Calendar.YEAR, Integer.parseInt(year));
        cal_start.set(Calendar.MONTH, Integer.parseInt(month) - 1);
        cal_start.set(Calendar.DAY_OF_MONTH, 1);

        Calendar cal_end = Calendar.getInstance();
        cal_end.set(Calendar.YEAR, Integer.parseInt(year));
        cal_end.set(Calendar.MONTH, Integer.parseInt(month) - 1);

        int monthdays = cal_end.getActualMaximum(Calendar.DAY_OF_MONTH);
        cal_end.set(Calendar.DAY_OF_MONTH, monthdays);

        return getWorkingDay(cal_start, cal_end);
    }

    public static int getWorkingDay(Calendar d1, Calendar d2) {
        int result = 0;
        int betweendays = getDaysBetween(d1, d2);
        int firstDayInWeek = d1.get(Calendar.DAY_OF_WEEK);
        //the 1st day is not start with sunday
        if (firstDayInWeek > 1) {
            result = 7 - firstDayInWeek;
            betweendays -= (result + 1);
        }
        result += betweendays / 7 * 5;

        int days = betweendays % 7;
        if (days > 0)
            result += days - 1;

        return result;
    }

    public static int getDaysBetween(java.util.Calendar d1, java.util.Calendar d2) {
        if (d1.after(d2)) { // swap dates so that d1 is start and d2 is end
            java.util.Calendar swap = d1;
            d1 = d2;
            d2 = swap;
        }
        int days = d2.get(java.util.Calendar.DAY_OF_YEAR) - d1.get(java.util.Calendar.DAY_OF_YEAR) + 1;
        int y2 = d2.get(java.util.Calendar.YEAR);
        if (d1.get(java.util.Calendar.YEAR) != y2) {
            d1 = (java.util.Calendar) d1.clone();
            do {
                days += d1.getActualMaximum(java.util.Calendar.DAY_OF_YEAR);
                d1.add(java.util.Calendar.YEAR, 1);
            } while (d1.get(java.util.Calendar.YEAR) != y2);
        }
        return days;
    }
}

Related

  1. getStartAndEndOfDay(Calendar calendar)
  2. getStartOfDay(Calendar cal)
  3. getThatMonday(Calendar cal)
  4. getTodayCalendar()
  5. getWorkingDay(Calendar beginDate, Calendar endDate)
  6. incrementDay(Calendar cal)
  7. incrementOneDay(Calendar calendar)
  8. isAfterDay(Calendar cal1, Calendar cal2)
  9. isAllDayEvent(Calendar dtStart, Calendar dtEnd)