Check if todays date is between two other dates

后端 未结 3 572
攒了一身酷
攒了一身酷 2021-01-24 06:27

I am trying to check if todays date is between START and STOP date of a period, Winter, summer, spring etc..

and if the todays date is between, lets say.. the winter per

3条回答
  •  失恋的感觉
    2021-01-24 07:03

    Remember that a variable can be overwritten - just as the year progresses through the seasons, your variable can as well - as long as we do it in order we'll end up on the correct one. This means we only have to test if our date is after the date that a season changes.

    // Since we're testing today's date
    // we use the current year timestamps
    $year = date('Y');
    $startSpring = strtotime("$year-03-01");
    $startSummer = strtotime("$year-06-01");
    $startAutum = strtotime("$year-09-01");
    $startWinter = strtotime("$year-12-01");
    
    $today = time();
    
    // The year starts with Winter
    $season = 'Winter';
    if($today > $startSpring) $season = 'Spring'; // Past the 1st day of spring?
    if($today > $startSummer) $season = 'Summer'; // Etc...
    if($today > $startAutumn) $season = 'Autumn';
    if($today > $startWinter) $season = 'Winter';
    
    echo 'It is currently '.$season;
    

    Here's the same logic cleaned up in a pretty function that will check any date for you and return the season:

    // Accepts an optional unix timestamp
    // Uses the current date by default
    function getSeason($test_date=FALSE){
        $test_date = $test_date ? $test_date : time();
    
        // Use the year of the date we're testing
        $year = date('Y', $test_date);
    
        // The year starts with Winter
        $season = 'Winter';
        if($test_date > strtotime("$year-03-01")) $season = 'Spring'; // Past the 1st day of spring?
        if($test_date > strtotime("$year-06-01")) $season = 'Summer'; // Etc...
        if($test_date > strtotime("$year-09-01")) $season = 'Autumn';
        if($test_date > strtotime("$year-12-01")) $season = 'Winter';
    
        return $season;
    }
    

提交回复
热议问题