dstbtam8732 2016-02-01 03:26
浏览 60
已采纳

检查日期是否在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-02-01 03: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

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

报告相同问题?

悬赏问题

  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化