Reputation: 45062
I am looking for the best way to get the last weekday from a particular date. The example I am using is what was the last workday before Christmas eve (24th Dec).
unfortunately this doesn't work:
echo date('l jS \of F Y h:i:s A', strtotime('last weekday before 24th December 2012'));
Upvotes: 10
Views: 4589
Reputation: 1
function getLastWorkingday(){
$year_month = date('Y-m');
$lastDay = date('N', strtotime('last day of '.$year_month));
$lastDayt = date('t', strtotime('last day of '.$year_month));
if($lastDay == 6){
$lastWorkingday = $lastDayt-1;
}elseif($lastDay == 7){
$lastWorkingday = $lastDayt-2;
}else{
$lastWorkingday = date('t');
}
return $lastWorkingday;
}
if( getLastWorkingday() == date('d') ){
// Do something
}
Upvotes: 0
Reputation: 5050
Have you tried something like this:
echo date('l jS \of F Y h:i:s A', strtotime('24th December 2012 previous weekday'));
This will output something like Friday 21st of December 2012 12:00:00 AM
using PHP 5.3.19
Heres another way you could go about this, its not the prettiest thing but it should work:
$date = '24th December 2012';
$dateN = intval(date('N', strtotime($date)));
if ($dateN === 1) {
$prevWeekday = date('l jS \of F Y h:i:s A', strtotime($date . '-3 days'));
} else if ($dateN === 7) {
$prevWeekday = date('l jS \of F Y h:i:s A', strtotime($date . '-2 day'));
} else {
$prevWeekday = date('l jS \of F Y h:i:s A', strtotime($date . '-1 day'));
}
echo $prevWeekday;
Upvotes: 1
Reputation: 51970
Just remove before
and your example will work fine (as of PHP 5.2.0). The absolute date part (24th December 2012
) is processed first, followed by the relative part (last weekday
), as per the relative formats documentation.
Original
last weekday before 24th December 2012
Correct
last weekday 24th December 2012
Per the other answers, previous
and last
when used as in the question behave in the exact same way; meaning the immediately preceding occurrence of something (in this case, a weekday). last
does have another special meaning when used in the style of last dayname of
, which is not being used in the question.
Reference:
Upvotes: 9