dstbtam8732 2016-02-01 03: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-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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀