user4563161
user4563161

Reputation:

PHP date "last weekday" outputting the wrong month

I'm trying to get the last weekday of the current month using the code below.

I was expecting this to behave just like all of the other operators like last friday of and output the last weekday of this month. but instead its outputting the last weekday of the previous month.

I know that I can rectify this by using modify( '+1 month' ) but why? Why is it the other operators like last tuesday of work fine but last weekday needs to be bosted by 1 month?

<?php
// outputs the previous months date
$gettoday = date( "Y-m-01" );
$freqdate = date( 'Y-m-d', strtotime( 'last weekday '.$gettoday ) );
echo 'next '.$freqdate;

//get the correct date
$gettoday = new DateTime( $gettoday );
$gettoday->modify( '+1 month' );
$gettoday = date_format( $gettoday, 'Y-m-01' );
$freqdate = date( 'Y-m-d', strtotime( $gettoday . ' last weekday' ) );
echo 'next '.$freqdate;
?>

Upvotes: 1

Views: 365

Answers (1)

C3roe
C3roe

Reputation: 96316

It appears you had a wrong understanding of what “last” actually means here.

That has nothing to do with the last day or week of the month - it is “last” as in “the closest previous one”.

You can start with something like strtotime('last day of 2020-03') - that would give you 31 Mar 2020, which is a Tuesday.

If you then check what day of the week this is, and it would be either a Saturday or a Sunday - then you can go last friday on that value again, to land on the latest week day of the month.

Edit:

Example for all months of 2020

for($i=1; $i<13; ++$i) {
  $year_month = '2020-'.$i;
  $last_of_month = strtotime('last day of '.$year_month);
  $weekday = date('N', $last_of_month);
  if($weekday < 6) {
    echo 'last weekday of ', $year_month, ' is ', date('Y-m-d, l', $last_of_month), "<br>\n";
  }
  else {
    $last_weekday_of_month = strtotime('last friday', $last_of_month);
    echo 'last day of ', $year_month, ' is ', date('Y-m-d, l', $last_of_month), ' - last weekday of ', $year_month, ' is ', date('Y-m-d, l', $last_weekday_of_month), "<br>\n";
  }
}

This will get you the following output:

last weekday of 2020-1 is 2020-01-31, Friday
last day of 2020-2 is 2020-02-29, Saturday - last weekday of 2020-2 is 2020-02-28, Friday
last weekday of 2020-3 is 2020-03-31, Tuesday
last weekday of 2020-4 is 2020-04-30, Thursday
last day of 2020-5 is 2020-05-31, Sunday - last weekday of 2020-5 is 2020-05-29, Friday
last weekday of 2020-6 is 2020-06-30, Tuesday
last weekday of 2020-7 is 2020-07-31, Friday
last weekday of 2020-8 is 2020-08-31, Monday
last weekday of 2020-9 is 2020-09-30, Wednesday
last day of 2020-10 is 2020-10-31, Saturday - last weekday of 2020-10 is 2020-10-30, Friday
last weekday of 2020-11 is 2020-11-30, Monday
last weekday of 2020-12 is 2020-12-31, Thursday

Upvotes: 3

Related Questions