当前位置: 首页 > 面试题库 >

两个日期之间的差异,仅包括工作日(即,不包括周末和节假日)

卜阳
2023-03-14
问题内容

如何获得两个工作日之间的工作天数java.util.Date,即不包括周末和节假日?假期是指法律认可的假期。由于每个国家/地区的假期不同,因此必须取决于国家/地区。

例如,由于介于两者之间的周末,2012-08-27 - 2012-08-24应返回1而不是3

我已经看过Jollyday和ObjectLab-
Kit
,但是我不能让它们满足我的需要。我的意思是,他们两个都有很多有趣的方法,但是找不到类似getBusinessDaysCount(Date d1, Date d2)…的东西。


问题答案:

最后是基于CalendarAPI 的解决方案:

/**
 * Handles holidays by country.
 */
public enum Holidays {

  /**
   * See <a href="http://www.wikiwand.com/en/Public_holidays_in_France">http://www.wikiwand.com/en/Public_holidays_in_France</a>.
   */
  FRANCE {

    @Override
    protected void addFixedHolidays(Set<Holiday> holidays) {
      holidays.add(new Holiday(Calendar.JANUARY, 1));
      holidays.add(new Holiday(Calendar.MAY, 1));
      holidays.add(new Holiday(Calendar.MAY, 8));
      holidays.add(new Holiday(Calendar.JULY, 14));
      holidays.add(new Holiday(Calendar.AUGUST, 15));
      holidays.add(new Holiday(Calendar.NOVEMBER, 1));
      holidays.add(new Holiday(Calendar.NOVEMBER, 11));
      holidays.add(new Holiday(Calendar.DECEMBER, 25));
    }

    @Override
    protected void addVariableHolidays(int year, Set<Holiday> holidays) {
      Date easterSunday = getEasterSunday(year);
      holidays.add(new Holiday(getEasterMonday(easterSunday)));
      holidays.add(new Holiday(getAscensionThursday(easterSunday)));
      holidays.add(new Holiday(getPentecostMonday(easterSunday)));
    }

  },

  /**
   * See <a href="http://www.wikiwand.com/en/Public_holidays_in_the_United_Kingdom">http://www.wikiwand.com/en/Public_holidays_in_the_United_Kingdom</a>.
   */
  ENGLAND {

    @Override
    protected void addFixedHolidays(Set<Holiday> holidays) {
      holidays.add(new Holiday(Calendar.JANUARY, 1));
      holidays.add(new Holiday(Calendar.DECEMBER, 25));
      holidays.add(new Holiday(Calendar.DECEMBER, 26));
    }

    @Override
    protected void addVariableHolidays(int year, Set<Holiday> holidays) {
      Date easterSunday = getEasterSunday(year);
      holidays.add(new Holiday(getGoodFriday(easterSunday)));
      holidays.add(new Holiday(getEasterMonday(easterSunday)));
      holidays.add(new Holiday(get(WeekdayIndex.FIRST, Calendar.MONDAY, Calendar.MAY, year)));
      holidays.add(new Holiday(get(WeekdayIndex.LAST, Calendar.MONDAY, Calendar.MAY, year)));
      holidays.add(new Holiday(get(WeekdayIndex.LAST, Calendar.MONDAY, Calendar.AUGUST, year)));
      Holiday christmasDay = new Holiday(Calendar.DECEMBER, 25);
      if (christmasDay.isWeekend(year)) {
        holidays.add(new Holiday(Calendar.DECEMBER, 27));
      }
      Holiday boxingDay = new Holiday(Calendar.DECEMBER, 26);
      if (boxingDay.isWeekend(year)) {
        holidays.add(new Holiday(Calendar.DECEMBER, 28));
      }
    }

  };

  public class HolidayException extends Exception {

    private static final long serialVersionUID = 1L;

    private HolidayException(String message) {
      super(message);
    }

  }

  /**
   * A holiday is defined by a {@link Calendar#MONTH} and a {@link Calendar#DAY_OF_MONTH}.
   */
  private class Holiday {

    private final int day;
    private final int month;

    public Holiday(Date date) {
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      month = calendar.get(Calendar.MONTH);
      day = calendar.get(Calendar.DAY_OF_MONTH);
    }

    public Holiday(int month, int day) {
      this.month = month;
      this.day = day;
    }

    public Date toDate(int year) {
      Calendar calendar = Calendar.getInstance();
      calendar.set(year, month, day);
      return calendar.getTime();
    }

    public boolean isWeekend(int year) {
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(toDate(year));
      int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
      return dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY;
    }

    @Override
    public boolean equals(Object obj) {
      if (this == obj) {
        return true;
      } else if (!(obj instanceof Holiday)) {
        return false;
      } else {
        Holiday holiday = (Holiday) obj;
        return holiday.month == month && holiday.day == day;
      }
    }

    @Override
    public int hashCode() {
      return Arrays.hashCode(new int[] { month, day });
    }

  }

  /**
   * Use with {@link Holidays#get(WeekdayIndex, int, int, int)}.<br />
   * <br />
   * Example: <code>Holidays.get(WeekdayIndex.FIRST, Calendar.MONDAY, Calendar.MAY, 2000)</code>.
   */
  public enum WeekdayIndex {

    FIRST(1), SECOND(2), THIRD(3), FOURTH(4), LAST(null);

    private final Integer index;

    private WeekdayIndex(Integer index) {
      this.index = index;
    }

    private boolean is(int count) {
      return index != null && index == count;
    }

  }

  private final Set<Holiday> fixedHolidays = new HashSet<Holiday>();

  private final Map<Integer, Set<Holiday>> variableHolidays = new HashMap<Integer, Set<Holiday>>();

  private Holidays() {
    addFixedHolidays(fixedHolidays);
  }

  protected abstract void addFixedHolidays(Set<Holiday> holidays);

  protected abstract void addVariableHolidays(int year, Set<Holiday> holidays);

  /**
   * Returns the number of business days between two dates.
   * 
   * @param d1
   *          The first date.
   * @param d2
   *          The second date.
   * @return The number of business days between the two provided dates.
   * @throws HolidayException
   *           If <code>d1</code> or <code>d2</code> is not a business day.
   */
  public int getBusinessDayCount(Date d1, Date d2) throws HolidayException {
    Calendar calendar = Calendar.getInstance();
    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    try {
      d1 = formatter.parse(formatter.format(d1));
      d2 = formatter.parse(formatter.format(d2));
    } catch (ParseException ignore) {
      // cannot happen
    }
    if (!isBusinessDay(d1) || !isBusinessDay(d2)) {
      throw new HolidayException("Input dates must be business days");
    }
    int businessDayCount = 0;
    Date min = d1.before(d2) ? d1 : d2;
    Date max = min.equals(d2) ? d1 : d2;
    calendar.setTime(min);
    while (calendar.getTime().before(max)) {
      calendar.add(Calendar.DAY_OF_MONTH, 1);
      if (isBusinessDay(calendar.getTime())) {
        businessDayCount++;
      }
    }
    return businessDayCount;
  }

  /**
   * Returns whether a date is a business day.
   * 
   * @param date
   *          The date.
   * @return <code>true</code> if the <code>date</code> is a business day, <code>false</code> otherwise.
   */
  public boolean isBusinessDay(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
    if (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY) {
      return false;
    } else if (isFixedHoliday(date)) {
      return false;
    } else if (isVariableHoliday(date)) {
      return false;
    }
    return true;
  }

  private boolean isFixedHoliday(Date date) {
    return fixedHolidays.contains(new Holiday(date));
  }

  private boolean isVariableHoliday(Date date) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int year = calendar.get(Calendar.YEAR);
    Set<Holiday> yearHolidays;
    if (!variableHolidays.containsKey(year)) {
      // variable holidays have not been calculated for this year yet
      yearHolidays = new HashSet<Holiday>();
      addVariableHolidays(year, yearHolidays);
      variableHolidays.put(year, yearHolidays);
    } else {
      yearHolidays = variableHolidays.get(year);
    }
    return yearHolidays.contains(new Holiday(date));
  }

  public static Date getEasterSunday(int year) {
    // credits: https://www.wikiwand.com/en/Computus#/Anonymous_Gregorian_algorithm
    Calendar calendar = Calendar.getInstance();
    int initialYear = year;
    if (year < 1900) {
      year += 1900;
    }
    int a = year % 19;
    int b = year / 100;
    int c = year % 100;
    int d = b / 4;
    int e = b % 4;
    int f = (b + 8) / 25;
    int g = (b - f + 1) / 3;
    int h = (19 * a + b - d - g + 15) % 30;
    int i = c / 4;
    int j = c % 4;
    int k = (32 + 2 * e + 2 * i - h - j) % 7;
    int l = (a + 11 * h + 22 * k) / 451;
    int m = (h + k - 7 * l + 114) % 31;
    int month = (h + k - 7 * l + 114) / 31 - 1;
    int day = m + 1;
    calendar.set(initialYear, month, day);
    return calendar.getTime();
  }

  public static Date getGoodFriday(Date easterSunday) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(easterSunday);
    calendar.add(Calendar.DAY_OF_MONTH, -2);
    return calendar.getTime();
  }

  public static Date getEasterMonday(Date easterSunday) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(easterSunday);
    calendar.add(Calendar.DAY_OF_MONTH, 1);
    return calendar.getTime();
  }

  public static Date getAscensionThursday(Date easterSunday) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(easterSunday);
    calendar.add(Calendar.DAY_OF_MONTH, 39);
    return calendar.getTime();
  }

  public static Date getPentecostMonday(Date easterSunday) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(easterSunday);
    calendar.add(Calendar.DAY_OF_MONTH, 50);
    return calendar.getTime();
  }

  public static Date get(WeekdayIndex weekdayIndex, int dayOfWeek, int month, int year) {
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, 1);
    int count = 0;
    Date last = null;
    do {
      if (calendar.get(Calendar.DAY_OF_WEEK) == dayOfWeek) {
        count++;
        last = calendar.getTime();
        if (weekdayIndex.is(count)) {
          return last;
        }
      }
      calendar.add(Calendar.DAY_OF_MONTH, 1);
    } while (calendar.get(Calendar.MONTH) == month);
    if (weekdayIndex.equals(WeekdayIndex.LAST)) {
      return last;
    }
    return null;
  }

}

致电:

Holidays.FRANCE.getBusinessDayCount(d1, d2);


 类似资料:
  • 问题内容: 嗨,我正在使用jquery-uidatepicker选择date和date.js来查找两个日期之间的差异。 现在的问题是我想从计算中排除周末(周六和周日)。我该怎么办? 例如,用户选择开始日期(13/8/2010)和结束日期(16/8/2010)。由于14/8/2010和15/8/2010是工作日,而不是总共4天,所以我希望只有2天。 这是即时消息正在使用的代码: 问题答案: 也许其他

  • 问题内容: 我有一个代码,可以使用np.busdaycount计算除周末以外的日期差异,但是我需要在我无法获得的小时数内。 除周末外,我的工作时间为小时。喜欢 问题 Inflow_date_time = 2019-08-01 23:22:46 End_date_time = 2019-08-05 17:43:51预期小时数42小时(1 + 24 + 17) Inflow_date_time = 2

  • 问题内容: 给定以下日期: 和一个静态变量: 我需要创建一个数组,如: 周末除外。 不,这不是功课…出于某种原因,我今天无法直截了当。 问题答案: 对于PHP> = 5.3.0,请使用DatePeriod类。不幸的是,几乎没有记录。

  • 问题内容: 我需要计算MySQL中两个日期之间的差异(以天为单位),不包括周末(星期六和星期日)。也就是说,天数差减去两者之间的周六和周日数。 目前,我只是使用以下方法计算天数: 此收益,但我想排除周末,所以我想(因为第3和4、10、11和17日是周末)。 我不知道从哪里开始。我知道该功能和所有相关功能,但是我不知道如何在此上下文中使用它们。 问题答案: 插图: 伪代码:

  • 问题内容: 我需要计算两个日期之间的天数(工作日),不包括周末(最重要)和假期 但是,我不知道该如何在MySQL中进行操作,我发现本文计算了两个日期之间的天数,不包括周末(仅MySQL)。我无法弄清楚如何在mysql中进行功能查询,能否提供一些有关如何使用mysql查询实现此功能的信息。如果我想念什么,请告诉我。 [编辑] 问题答案: 您可能要尝试以下操作: 计算工作日数(从此处获取) 这为您提供

  • 问题内容: 我在Spring 3.0项目中使用Joda time api计算日期。现在我有一个开始日期和结束日期,我想在这两个日期之间得到每天的周末,星期六或星期日。我该如何实现? 我看了这篇Joda的时间-两个日期之间的所有星期一。它提供了一些指导,但在如何排除两个日期方面仍然含糊。 问题答案: 我想你的问题是如何 在两个日期之间的周末,星期六或星期日除外的每一天获取。 解决方案 :