【问题标题】:Display all the week numbers between two dates in PHP [duplicate]在PHP中显示两个日期之间的所有周数[重复]
【发布时间】:2011-09-21 07:17:37
【问题描述】:

谁能告诉如何在 PHP 中显示两个日期之间涵盖的所有周数。日期可能是不同的年份。

如果我使用开始日期为“2011-09-16”,结束日期为“2011-09-21”,它将显示第 37 周和第 38 周。

【问题讨论】:

  • 到目前为止你有没有尝试过?
  • 这个问题被标记为重复。我不认为这些问题是重复的,因为这个问题侧重于周数,而 the other 侧重于一段时间内的日期。

标签: php


【解决方案1】:

你可以使用这样的东西......

$startTime = strtotime('2011-12-12');
$endTime = strtotime('2012-02-01');

$weeks = array();

while ($startTime < $endTime) {  
    $weeks[] = date('W', $startTime); 
    $startTime += strtotime('+1 week', 0);
}

var_dump($weeks);

CodePad.

输出

array(8) {
  [0]=>
  string(2) "50"
  [1]=>
  string(2) "51"
  [2]=>
  string(2) "52"
  [3]=>
  string(2) "01"
  [4]=>
  string(2) "02"
  [5]=>
  string(2) "03"
  [6]=>
  string(2) "04"
  [7]=>
  string(2) "05"
}

【讨论】:

    【解决方案2】:

    使用新的日期时间组件 (PHP >= 5.3.0),您可以结合使用 DateTimeDateIntervalDatePeriod 来获取给定时间跨度内所有周的迭代器。

    $p = new DatePeriod(
        new DateTime('2011-12-01'), 
        new DateInterval('P1W'), 
        new DateTime('2012-02-01')
    );
    foreach ($p as $w) {
        var_dump($w->format('W'));
    }
    
    /*
    string(2) "48"
    string(2) "49"
    string(2) "50"
    string(2) "51"
    string(2) "52"
    string(2) "01"
    string(2) "02"
    string(2) "03"
    string(2) "04"
    */
    

    【讨论】:

      【解决方案3】:

      在循环中使用date( 'W' )strtotime( '+1 week', $time ) 的组合

      【讨论】:

        猜你喜欢
        • 2020-05-01
        • 1970-01-01
        • 2015-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-16
        • 2011-11-08
        相关资源
        最近更新 更多