0

我试图在两个星期之间获得最后一个星期日 - 为了避免 DST。

换句话说:开始一个时间范围 - 从三月的最后一个星期日到十月的最后一个星期日。

这是我的代码:

   $heloo = gmdate('U');
   if ( (date("W", $heloo) >= 12) 
       && (date("W", $heloo) <= 43)
       && (date("N", $heloo) == 7) ) {
    echo "YES Day is: ".date("N", $heloo). "<br />
           Week is: ". date("W", $heloo);
  } else { 
  echo "NO Day is: ".date("N", $heloo). "<br />Week is: ". date("W", $heloo); 
 }

几周似乎工作得很好,但日子根本不工作。您能否指出正确的方向或建议在哪里获得帮助?

:-)

4

1 回答 1

1

试试这段简单的代码:

  function rangeSundays($year, $month_start, $month_end) {
    $res = array();
    for ($i = $month_start; $i <= $month_end; $i++) {
      $dt = strtotime('last sunday of this month', strtotime("$year-$i-1"));
      $res[] = date('Y-m-d', $dt);
      } 
    return $res;
    }

所以,以这种方式使用它

$date_array = rangeSundays(2011, 3, 10); // year, start month, end month
print_r($date_array);

输出

Array
    (
        [0] => 2011-03-27
        [1] => 2011-04-24
        [2] => 2011-05-29
        [3] => 2011-06-26
        [4] => 2011-07-31
        [5] => 2011-08-28
        [6] => 2011-09-25
        [7] => 2011-10-30
    )

此外,如果您的 php 配置 (php.ini) 中未设置默认时区,请在脚本开头添加类似这样的内容,以避免在 PHP 中引发警告。

date_default_timezone_set('UTC'); // or any other time zone

将此结果打印到屏幕使用

$date_array = rangeSundays(2011, 3, 10);
foreach($date_array as $x) {
  echo "$x<br/>";
  }


如果你想在不使用函数的情况下做到这一点

$year = 2011; // or which year you want
$month_start = 3; // for starting month; March in this case
$month_end = 10; // for ending month; October in this case

$res = array();
for ($i = $month_start; $i <= $month_end; $i++) {
  $dt = strtotime('last sunday of this month', strtotime("$year-$i-1"));
  $res[] = date('Y-m-d', $dt);
  }

foreach($res as $sunday) {
  echo "$sunday<br />";
  }

输出

2011-03-27
2011-04-24
2011-05-29
2011-06-26
2011-07-31
2011-08-28
2011-09-25
2011-10-30

注意:在这种情况下,DST 不会影响日期。

您的代码看起来像不必要的复杂性:)

于 2011-04-06T08:12:40.823 回答