dstbtam8732 2016-01-31 19:26
浏览 61
已采纳

检查日期是否在PHP strtotime范围内

I have searched through SO but the answers that I've tried doesn't seem to solve my problem. I have this simple code snippet where the user will input a numeric date, and a month, and the app will return the corresponding Zodiac Sign.

$birthdate = $_POST["birthdate"];
$birthmonth = (ucwords(strtolower($_POST["month"])))

//validations here. . .

    $tmp = $birthmonth . " " . $birthdate;
    $tmp2 = date_create_from_format('M j', $tmp);

    $formatted_dob = date_format($tmp2, 'm-d-Y'); 
    $dob = strtotime($formatted_dob);

    echo $formatted_dob;

    if ($dob >= strtotime('01-20-2016') && $dob <= strtotime('02-18-2016')) {
        echo "Aquarius"; 
    } elseif ($dob >= strtotime('02-19-2016') && $dob <= strtotime('03-20-2016')){          
        echo "Pisces";
    } 

Those echo stuff outside the if-else block are working fine, however if I input a value of 25 and February (which later on results to 02-25-2016), it always output Aquarius. How do you compare two strtotimevalues?

I've tried using DateTime object but it only gives me an error, which is another story. Thanks in advance.

  • 写回答

1条回答 默认 最新

  • drti52047 2016-01-31 19:52
    关注

    Edited: Change the order of your date (*your format on your date 01-20-2016 m-d-Y that's why when you convert it it becomes 1970-01-01 'Y-m-d' but if you change it into 2016-01-20 'Y-m-d' on your date range the code will work just fine in else-if.

    $birthdate = $_POST["birthdate"];
    $birthmonth = (ucwords(strtolower($_POST["month"])))
    
    //validations here. . .
    
        $tmp = $birthmonth . " " . $birthdate;
        $tmp2 = date_create_from_format('M j', $tmp);
    
        $formatted_dob = date_format($tmp2, 'm-d-Y'); 
        $dob = strtotime($formatted_dob);
    
        echo $formatted_dob;
    $dobcompare = date_create(date('m/d/Y', $dob));
    $aqstartdate = date_create(date('m/d/Y', strtotime('2016-01-20')));
    $aqenddate = date_create(date('m/d/Y', strtotime('2016-02-18')));
    $pistartdate = date_create(date('m/d/Y', strtotime('2016-02-19')));
    $pienddate = date_create(date('m/d/Y', strtotime('2016-03-20')));
    
        if ($dobcompare >= $aqstartdate && $dobcompare <= $aqenddate) {
            echo "Aquarius"; 
        }
        elseif ($dobcompare >= $pistartdate && $dobcompare <= $pienddate) {
            echo "Pisces"; 
        } else {          
            echo "IDK";
        } 
    

    Modify it in your need.

    This is the example enter link description here

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?