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'));
Use strtotime() function to get the first day of week using PHP. This function returns the default time variable timestamp and then use date() function to convert timestamp date into understandable date. strtotime() Function: The strtotime() function returns the result in timestamp by parsing the time string.
date("m/d/Y", strtotime("last week monday")); date("m/d/Y", strtotime("last week sunday")); It will give the date of Last week's Monday and Sunday. Save this answer.
Just use the date relative format: $date = new DateTime("last monday"); What would be the last Monday that passed. The strtotime function accepts a string, in the format "US English date", and parse it into a timestamp , making it possible to add dates, get specific days, and count other features.
By subtracting 7 days from the current date, we get last week's date.
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:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With