Last weekday from specific date in php
Asked Answered
S

3

10

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'));
Sims answered 19/12, 2012 at 19:54 Comment(0)
D
9

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:

Danit answered 19/12, 2012 at 20:12 Comment(0)
J
1

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;
Jackpot answered 19/12, 2012 at 19:59 Comment(0)
J
0
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
}
Journalist answered 23/10, 2023 at 8:30 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Arminius

© 2022 - 2024 — McMap. All rights reserved.