Reputation: 143
I have tried to get the current week thursday's date using the code below
date('m/d/y',strtotime('thursday this week'));
As the above how can i get current months all thursday dates in php.
Upvotes: 0
Views: 252
Reputation: 51970
It is advisable to make use of the improved date and time abilities that came with PHP 5.3.0. Namely, the DatePeriod
and DateInterval
classes.
<?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;
}
Edit
More complex filtering can be done in a variety of ways, but here is a simple approach to showing every Tuesday and Thursday in the month.
...
$interval = new DateInterval('P1D');
...
foreach ($period as $date) {
if (in_array($date->format('D'), array('Tue', 'Thu'), TRUE)) {
echo $date->format('c') . PHP_EOL;
}
}
Upvotes: 2
Reputation: 37365
You can filter your dates like this:
$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;
});
Alternative way to get $rgTime
will be:
$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;
}
}
-now, if you want to get specific format, like Y-m-d
, that will be:
$rgTime = array_map(function($x)
{
return date('Y-m-d', $x);
}, $rgTime);
Edit
If you want to have several week days, it's also easy. For first sample that will be:
$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);
});
Upvotes: 1
Reputation: 1371
try this. Should work :)
<?
$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);
?>
Upvotes: 0