Reputation: 377
I am trying to figure out a function that will return true if a DateTime date is the last weekday(Mon-Fri) of a month. This is what I have so far. Any suggestions on improving?
For example, if I pass in October 30, 2020 it should return true, because Friday the 30th is the last weekday (Mon-Fri) that occurs in October.
For example, if I pass in October 31, 2020 it should return false, because the 31st is a Saturday (not Mon-Fri)
function isLastWeekday($dateObject){
$last_day = new DateTime($dateObject->format( 'Y-m-t' ));
$last_day_of_month = $last_day->format( 't' );
switch( $last_day->format('N') ) {
case 6:
$last_day_of_month += -1;
break;
case 7:
$last_day_of_month += -2;
break;
}
if( $dateObject->format( 'Y-m-d' ) == $last_day->format( 'Y-m-' ).$last_day_of_month ){
return true;
}else{
return false;
}
}
Thanks, Ben
Upvotes: 0
Views: 176
Reputation: 57141
Using strtotime()
and the relative date formats, this takes the date passed in (assuming a DateTime object) and formats it to the begining of next month and modifies it by last weekday
, so for October 2020, this will give 2020-10-30 as the last weekday. This is then compared against the timestamp from the original date passed in...
function isLastWeekday($dateObject){
$end = clone $dateObject;
$end->modify('first day of next month');
return strtotime( $end->format( 'Y-m-d' ).' last weekday')
== $dateObject->getTimeStamp();
}
Had a few issues with using the last day of month, so this is why it moves it on a month
Or just using DateTime objects...
function isLastWeekday($dateObject){
$end = clone $dateObject;
$end->modify('first day of next month')->modify('last weekday');
return $end == $dateObject;
}
Upvotes: 1