試圖讓下面我如何找到當月thurdays在PHP
date('m/d/y',strtotime('thursday this week'));
使用的代碼本週週四的日期作爲上述我怎樣才能獲得當月的PHP中的所有周四日期。
試圖讓下面我如何找到當月thurdays在PHP
date('m/d/y',strtotime('thursday this week'));
使用的代碼本週週四的日期作爲上述我怎樣才能獲得當月的PHP中的所有周四日期。
您可以過濾日期是這樣的:
$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);
});
試試這個。應該工作:)
<?
$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);
?>
建議使用PHP 5.3.0附帶的改進的日期和時間功能。即,DatePeriod
和DateInterval
類。
<?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;
}
}
實際上,在我的應用程序中,我使用了一種基於日曆的產品。因爲我只能展示當前的Thurdays產品。所以我問了這個問題。 – mangala