Search code examples
php

strtotime time/date in PHP switch/case statement


I've created a PHP switch / case statement:

switch(true)
{
    case ($eff >= '10/2017'):
        echo "Greater than 10-2017";
        break;
    case ($eff <= '09/2017'):
        echo "Less thank 10-2017";
        break;                          
    default:
        echo '';
        break;
}

I'm using strtotime to cut down a date from 08/01/2017 to just 08/2017 like this:

$eff = date("m/Y", strtotime($userinfo['ExpDate']));

Unfortunately when I use this to create my case statement it doesn't give me the conditional output. I was hoping for when using a > or < operator and just defaults to the first case statement.

How do I use this to properly use greater/less than?


Solution

  • You can use a solution like the following:

    <?php
    $eff = date("m/Y", strtotime('10/01/2017'));
    $eff = date_create_from_format('m/Y', $eff);
    
    switch(true)
    {
        case (date_create_from_format('m/Y', '10/2017')->diff($eff)->format('%R%m') >= 0):
            echo "Greater than 10-2017";
            break;
        case (date_create_from_format('m/Y', '09/2017')->diff($eff)->format('%R%m') <= 0):
            echo "Less thank 10-2017";
            break;                          
        default:
            echo '';
            break;
    }
    

    demo: https://ideone.com/Z2un3C / some tests: https://3v4l.org/YP1Ub