Search code examples
phpdatedate-comparison

Quicker way for date comparing in PHP


Currently I'm doing something like the following

if(date("H") > 23) {
    if(date("H") < 24) {
        if(date("i") < 10) {
            if(date("i") < 20) {
                //perform an action if it's between 11:10pm and 11:20pm
            }
        }
    }
}

What's a quicker and cleaner way of perfoming such if statements?


Solution

  • Not a whole lot less code but probably easier to read:

    $now   = new DateTime();
    $early = new DateTime('23:10');
    $late  = new DateTime('23:20');
    if ($now > $early && $now < $late) {
        //perform an action if it's between 11:10pm and 11:20pm
    }