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 孟德尔随机化结果不一致
  • ¥15 深度学习残差模块模型
  • ¥50 怎么判断同步时序逻辑电路和异步时序逻辑电路
  • ¥15 差动电流二次谐波的含量Matlab计算
  • ¥15 Can/caned 总线错误问题,错误显示控制器要发1,结果总线检测到0
  • ¥15 C#如何调用串口数据
  • ¥15 MATLAB与单片机串口通信
  • ¥15 L76k模块的GPS的使用
  • ¥15 请帮我看一看数电项目如何设计
  • ¥23 (标签-bug|关键词-密码错误加密)