【问题标题】:Calculate Business Days in Month with Javascript使用 Javascript 计算每月的工作日
【发布时间】:2012-03-08 01:24:01
【问题描述】:

我正在尝试做两件事。

  1. 根据当天计算给定月份迄今为止的工作日数(即今天是 2012 年 3 月 7 日,因此,已经过去了 5 个工作日)
  2. 根据当天计算给定月份的工作日数(即今天是 2012 年 3 月 7 日,因此,本月还有 17 个工作日。

我们将不胜感激。

编辑: 到目前为止,这是我尝试过的:

function isWeekday(year, month, day) {var day = new Date(year, month, day).getDay();return day !=0 && day !=6;}
function getWeekdaysInMonth(month, year) {var days = daysInMonth(month, year);var weekdays = 0;for(var i=0; i< days; i++) {if (isWeekday(year, month, i+1)) weekdays++;}return weekdays;}
function calcBusinessDays(dDate1, dDate2) {
    var iWeeks, iDateDiff, iAdjust = 0;
    if (dDate2 < dDate1) return -1;                 // error code if dates transposed
    var iWeekday1 = dDate1.getDay();                // day of week
    var iWeekday2 = dDate2.getDay();
    iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1;   // change Sunday from 0 to 7
    iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;
    if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1;  // adjustment if both days on weekend
    iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1;    // only count weekdays
    iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;
    // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
    iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)
    if (iWeekday1 <= iWeekday2) {
    iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
    } else {
    iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
    }
    iDateDiff -= iAdjust                            // take into account both days on weekend
    return (iDateDiff + 1);                         // add 1 because dates are inclusive
}

不太清楚如何将所有这些放在一起以使工作日过去和工作日结束。

【问题讨论】:

  • 到目前为止您尝试过什么?您尝试的解决方案具体是什么给您带来了麻烦?
  • 你也要考虑假期吗?
  • Maerics 我在上面更新了我的请求。雅各布,假期并不重要。
  • 向前/向后循环并将工作日计算到月初/月底(包括第 1-5 天)会非常简单。

标签: javascript function date days


【解决方案1】:

这是一个非常简单的函数,它只循环了几天,应该足够快,因为它永远不必循环超过 31 次。如果当天是工作日,则按过去天数计算:

function businessDays(date) {

  // Copy date
  var t = new Date(date);
  // Remember the month number
  var m = date.getMonth();
  var d = date.getDate();
  var daysPast = 0, daysToGo = 0;
  var day;

  // Count past days
  while  (t.getMonth() == m) {
    day = t.getDay();
    daysPast += (day == 0 || day == 6)? 0 : 1;
    t.setDate(--d);
  }

  // Reset and count days to come
  t = new Date(date);
  t.setDate(t.getDate() + 1);
  d = t.getDate();

  while  (t.getMonth() == m) {
    day = t.getDay();
    daysToGo += (day == 0 || day == 6)? 0 : 1;
    t.setDate(++d);
  }
  return [daysPast, daysToGo];
}

alert(businessDays(new Date(2012,2,7))); // 7-Mar-2012 => 5, 17

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多