0

以下のコードを使用して、現在の週の木曜日の日付を取得しようとしました

date('m/d/y',strtotime('thursday this week'));

上記のように、PHPで木曜日のすべての日付を現在の月に取得するにはどうすればよいですか。

4

3 に答える 3

2

PHP 5.3.0 に付属する改良された日付と時刻の機能を利用することをお勧めします。つまり、DatePeriodandDateIntervalクラスです。

<?php

$start    = new DateTime('first thursday of this month');
$end      = new DateTime('first day of next month');
$interval = new DateInterval('P1W');
$period   = new DatePeriod($start, $interval , $end);

foreach ($period as $date) {
  echo $date->format('c') . PHP_EOL;
}

編集

より複雑なフィルタリングはさまざまな方法で実行できますが、ここでは月の毎週火曜日と木曜日を表示する簡単な方法を示します。

...
$interval = new DateInterval('P1D');
...
foreach ($period as $date) {
  if (in_array($date->format('D'), array('Tue', 'Thu'), TRUE)) {
      echo $date->format('c') . PHP_EOL;
    }
}
于 2013-10-03T13:04:37.807 に答える
1

次のように日付をフィルタリングできます。

$sDay   = 'Thursday';
$rgTime = array_filter(
   range(strtotime('first day of this month'), strtotime('last day of this month'), 3600*24),
   function($iTime) use ($sDay)
   {
      return date('l', $iTime) == $sDay;
   });

取得する別の方法は次の$rgTimeとおりです。

$rgNums = ['first', 'second', 'third', 'fourth', 'fifth'];
$rgTime = [];
$sDay   = 'Thursday';
foreach($rgNums as $sNum)
{
   $iTime = strtotime($sNum.' '.$sDay.' of this month');
   if(date('m', $iTime)==date('m'))
   {
      //this check is needed since not all months have 5 specific week days
      $rgTime[]=$iTime;
   }
}

-今、のような特定のフォーマットを取得したい場合は、次のようY-m-dになります。

$rgTime = array_map(function($x)
{
   return date('Y-m-d', $x);
}, $rgTime);

編集

平日を数日持ちたい場合も簡単です。最初のサンプルの場合:

$rgDays = ['Tuesday', 'Thursday'];
$rgTime = array_filter(
   range(strtotime('first day of this month'), strtotime('last day of this month'), 3600*24),
   function($iTime) use ($rgDays)
   {
      return in_array(date('l', $iTime), $rgDays);
   });
于 2013-10-03T12:01:55.723 に答える
0

これを試して。動作するはずです:)

    <?
    $curMonth = date("m");
    $start = strtotime("next Thursday - 42 days");
    for ($i=1; $i < 15; $i++){
        $week = $i*7;
        if (date("m",strtotime("next Thursday - 42 days + $week days")) == $curMonth ){
            $monthArr[] = date("m/d/y",strtotime("next Thursday - 42 days + $week days"));
        }
    }


print_r($monthArr);

?>

作業コード

于 2013-10-03T12:00:48.710 に答える