2013-10-03 32 views
0

試圖讓下面我如何找到當月thurdays在PHP

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

使用的代碼本週週四的日期作爲上述我怎樣才能獲得當月的PHP中的所有周四日期。

+0

實際上,在我的應用程序中,我使用了一種基於日曆的產品。因爲我只能展示當前的Thurdays產品。所以我問了這個問題。 – mangala

回答

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); 
    }); 
+0

嗨firend ..它的工作......我怎麼能在星期四和星期二的組合.. – mangala

+0

首先,你應該在你的問題中指定。 –

+0

雅我找到答案..謝謝...我已經使用相同的tuesdays ..和我合併這兩個數組。我得到當前幾個星期二和星期四... – mangala

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); 

?> 

WORKING CODE

2

建議使用PHP 5.3.0附帶的改進的日期和時間功能。即,DatePeriodDateInterval類。

<?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; 
    } 
}