【问题标题】:PHP: getting weekdays numbers of a given monthPHP:获取给定月份的工作日数
【发布时间】:2012-09-20 11:04:05
【问题描述】:

给定一个月份和一个工作日,我需要构建一个函数来检索所有星期一、星期二、星期三、星期四和星期五的天数。

假设我给这个月的函数,2012 年 9 月和工作日编号 1。该函数应该检索 2012 年 9 月的所有星期一,它们是:3、10、17 和 24

请注意,对我来说,第 1 个工作日是星期一,第 2 个是星期二,第 3 个是星期三,第 4 个是星期四,第 5 个是星期五。

到目前为止,我已经完成了:根据今天的日期获取一周的第一天(我在下面发布了函数)。但是我不知道如何以简单的方式从这里开始,我已经做了很多小时,我怀疑有更好的方法来做到这一点。你能告诉我怎么做吗?

  function getFirstDayOfWeek($date) {
    $getdate = getdate($date);

    // How many days ahead monday are we?
    switch ( $getdate['wday'] ) {
        case 0: // we are on sunday
            $days = 6;
            break;

        default: // any other day
            $days = $getdate['wday']-1;
            break;
    }

    $seconds = $days*24*60*60;
    $monday = date($getdate[0])-$seconds;

    return $monday;
}

非常感谢

【问题讨论】:

    标签: php date monthcalendar weekday


    【解决方案1】:

    不是很聪明,但对你有用:

    // sept. 2012
    $month = 9;
    
    // loop through month days
    for ($i = 1; $i <= 31; $i++) {
    
        // given month timestamp
        $timestamp = mktime(0, 0, 0, $month, $i, 2012);
    
        // to be sure we have not gone to the next month
        if (date("n", $timestamp) == $month) {
    
            // current day in the loop
            $day = date("N", $timestamp);
    
            // if this is between 1 to 5, weekdays, 1 = Monday, 5 = Friday
            if ($day == 1 OR $day <= 5) {
    
                // write it down now
                $days[$day][] = date("j", $timestamp);
            }
        }
    }
    
    // to see if it works :)
    print_r($days);
    

    【讨论】:

      猜你喜欢
      • 2012-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 2019-07-14
      • 2022-07-29
      • 1970-01-01
      • 2015-10-19
      • 2013-12-05
      相关资源
      最近更新 更多