【问题标题】:How to count all the Weeks of a month (including if 1st is saturday and the 31st is monday, meaning that would be 6 weeks)如何计算一个月的所有周数(包括第 1 天是星期六,第 31 天是星期一,这意味着 6 周)
【发布时间】:2017-04-06 07:28:15
【问题描述】:

所以我试图计算一个月中的周数,包括第 1 天是星期天或星期六而第 31 天是星期一的可能性,这意味着该月将有 6 周。 到目前为止,我得到了这个:

<?php
  for ($Month = 1; $Month <= 12; $Month++) 
  {
    if ($rstFase->fields['StartMonth'] <= $Month) 
    {
?>
       <div class="mounthDate">
<?php
       $timestamp = mktime(0, 0, 0, $x, 1, $i);
       while (date('n', $timestamp) == $x) 
       {
?>
          <div class="week"></div>
<?php
          $timestamp = strtotime("+1 week", $timestamp);
       }
?>
       </div>
<?php
     } 
     else 
     {
?>
        <div class="mounthDate"></div>
<?php
     }
  }

所以正确计算有 4 或 5 周的月份,但例如 2017 年 7 月有 6 个,它算作 5 个。

有什么想法吗?

【问题讨论】:

    标签: php html date


    【解决方案1】:

    取决于一周的哪一天开始,但这不是重点 :) 这是在做你需要的吗?

    <?php
    function weeks($month, $year){
    $firstday = date("w", mktime(0, 0, 0, $month, 1, $year)); 
    $lastday = date("t", mktime(0, 0, 0, $month, 1, $year)); 
    if ($firstday!=0) $count_weeks = 1 + ceil(($lastday-8+$firstday)/7);
    else $count_weeks = 1 + ceil(($lastday-1)/7);
    return $count_weeks;
    }
    
    echo weeks(1,2017)."<br/>"; /* 6 */
    echo weeks(7,2017)."<br/>"; /* 6 */
    ?>
    

    【讨论】:

    • 效果很好,你是怎么做到的很聪明,我试着做这样的事情,但我一定是做错了,因为我总是得到 0,谢谢你的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-12
    相关资源
    最近更新 更多