Search code examples
phpif-statementtimeconditional-statementsdayofweek

Conditional based on day of week and time range


I'm trying to find a solution to a conditional based on the day of the week and a time range within that day. I've managed to hunt down the code for the day of the week but I can't find how to incorporate a time frame within the day?

For example:

IF today is Monday AND between 2pm and 4pm THEN do THIS

This is what I have...

<?php   
date_default_timezone_set('Australia/Perth'); // PHP supported timezone
$script_tz = date_default_timezone_get();
// get current day:
$currentday = date('l'); ?>
<?php if ($currentday == Monday){ ?>
Monday
<?php } elseif ($currentday == Tuesday){ ?>
Tuesday
<?php } elseif ($currentday == Wednesday){ ?>
Wednesday
<?php } elseif ($currentday == Thursday){ ?>
Thursday
<?php } elseif ($currentday == Friday){ ?>
Friday
<?php } elseif ($currentday == Saturday){ ?>
Saturday
<?php } elseif ($currentday == Sunday){ ?>
Sunday
<?php } else { ?>
<?php } ?>

I'm not sure if this may help for the time frame? Check day of week and time


Solution

  • Basically this:

    <?php
    
    if (date('l') === 'Monday' && date('G') >= 2 && date('G') < 4) {
        // do something
    }
    
    

    You were missing quotes around the day names.

    The condition I wrote will evaluate to true on Monday between 2 PM and 4 PM (while 4 PM itself will not, e.g. the last allowed values is 3:59 PM).