【问题标题】:How can I figure out the number of week days in a month?如何计算一个月的工作日数?
【发布时间】:2011-02-10 21:55:08
【问题描述】:

我现在遇到了这个问题:给定一个月和一年,我需要知道它有多少工作日(即不包括周六和周日的天数)。

看起来很简单,但我很困惑。当然,我可以使用for 循环来解决它,并检查当天是周六还是周日,如果不增加计数器,但考虑到我很确定我可以得到这只是简单的愚蠢(和线性时间)去掉几个除法或模数。

对算法有任何想法吗?您可以随意使用 PHP 4.4.1 的所有功能。


编辑这是一个有效的for循环实现:

function weekdays_in_month($month, $year)
{
    $days_in_month = days_in_month($month); // days_in_month defined somewhere
    $first_day = date('w', mktime(0,0,0, $month, 1, $year));
    $counter = 0;
    for ($i = 0; $i < $days_in_month; $i++)
    {
        if (($first_day + $i + 1) % 7 >= 2)
            $counter++;
    }
    return $counter;
}

【问题讨论】:

  • 您希望它可以工作多久?如果您回溯到足够远以至于日历规则转换是一个问题,它会变得非常困难
  • @awoodland 是的,别担心。它需要从 2010 年左右开始工作。
  • days_in_month 还需要 $year 作为输入(考虑闰年)。
  • @John at CashCommons 我有没有提到我讨厌与日期打交道?
  • 是的,有很多小细节。我同意。

标签: date php4


【解决方案1】:

只需检查 29 日、30 日和 31 日的工作日(如果这些日期存在)。

加 20。

编辑你的函数:

function weekdays_in_month($month, $year)
{
    // NOTE: days_in_month needs $year as input also, to account for leap years
    $days_in_month = days_in_month($month, $year); // days_in_month defined somewhere
    $first_day = date('w', mktime(0,0,0, $month, 1, $year));
    $counter = 20;  // first 28 days of month always have 20 weekdays
    for ($i = 28; $i < $days_in_month; $i++)
    {
        if (($first_day + $i + 1) % 7 >= 2)
            $counter++;
    }
    return $counter;
}

【讨论】:

    【解决方案2】:

    您可以搜索一年中的第一个和最后一个星期日,然后将这两个日期的天数除以 7。对星期六做同样的事情,然后您可以从总数中减去星期日和星期六的数量一年中的天数。这是迄今为止我发现的最有效的解决方案。

    【讨论】:

      【解决方案3】:

      发现这个没有for循环的解决方案(未经http://www.phpbuilder.com/board/archive/index.php/t-10267313.html测试)

      function weekdays_in_month($month, $year)
      {
      $first = mktime(0,0,1,$month,1,$year);
      // The first day of the month is also the first day of the
      // remaining days after whole weeks are handled.
      list($first_day,$days) = explode(' ',date('w t',$first));
      $weeks = floor($days/7);
      $weekdays = $weeks*5;
      $remaining_days = $days-$weeks*7;
      
      if($remaining_days==0)
      return $weekdays; // Only happens most Februarys
      
      $weekdays += $remaining_days-1;
      // Neither starts on Sunday nor ends on Saturday
      if($first_day!=0 && ($first_day+$days-1)%7!=6)
      { // Adjust for weekend days.
      $weekdays += ($remaining_days<=(6-$first_day))-
      ($remaining_days>(6-$first_day));
      }
      
      
      return $weekdays;
      }
      

      【讨论】:

      • @MrBoJangles 如果美元符号伤害了你,我希望别人帮你理财。 :)
      • 我喜欢使用 jQuery 时的 $。我想这都是关于舒适区的。
      • floor($days/7) 可以是 4 以外的任何东西吗? :D
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 2010-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      相关资源
      最近更新 更多