0

DST を避けるために、最後の日曜日を 2 つの週番号の間で取得しようとしています。

順番に: 3 月の最後の日曜日から 10 月の最後の日曜日までの時間範囲を開始します。

これは私のコードです:

   $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 に答える