2016-02-01 89 views
0

我已經通過搜索,但我已經嘗試的答案似乎並沒有解決我的問題。 我有這個簡單的代碼片段,用戶將輸入數字日期和一個月,應用程序將返回相應的星座。檢查日期是否在範圍內的PHP strtotime

$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"; 
    } 

if-else塊之外的那些東西echo工作正常,但是,如果我輸入的25的值和二月(其稍後結果02-25-2016),它總是輸出Aquarius。你如何比較兩個strtotime值?

我試過使用DateTime對象,但它只給了我一個錯誤,這是另一回事。提前致謝。

回答

1

編輯: 更改日期的順序(*您的日期格式01-20-2016 mdY這就是爲什麼當您將其轉換爲1970-01-01'Ymd'時,爲什麼如果您將其更改爲2016-在日期範圍01-20「YMD」的代碼將在其他-如果工作得很好。

$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"; 
    } 

修改它在你的需要。

這是例子enter link description here

+0

的'date_create'工作正常,謝謝。但它不適用於其他 - 如果我有12個條件過濾那種驗證。 @LeeBalino – Cyval

+0

@Cyval更新了我的答案。請檢查它是否適用於您。 –

+0

我也試過你的代碼,只是改變你在strtotime上輸入的日期,將它從m-d-Y更改爲Y-m-d,因爲它是導致錯誤的原因之一。 @Cyval –

相關問題