Home » Php » Last weekday from specific date in php

Last weekday from specific date in php

Posted by: admin July 12, 2020 Leave a comment

Questions:

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'));
How to&Answers:

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:

Answer:

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;