2015-09-22 34 views
0

在我正在處理的應用程序中,用戶必須選擇至少5分鐘的日期/時間。爲此,我試圖執行檢查。下面是檢查當前時間和選定時間之間的時間差的代碼。PHP - 檢查所選時間是否至少5分鐘到將來

$cur_date = new DateTime(); 
    $cur_date = $cur_date->modify("+1 hours"); //fix the time since its an hour behind 
    $cur_date = $cur_date->format('m/d/Y g:i A'); 


    $to_time = strtotime($chosen_date); 
    $from_time = strtotime($cur_date); 
    echo round(abs($from_time - $to_time)/60,2). " minute"; //check the time difference 

這告訴我從選定時間和當前時間的時差(分鐘)。假設當前時間是2015年9月22日下午5點53分,所選時間是09/22/2015 5:41 PM - 它會告訴我12分鐘的差異。

我想知道的是我如何知道這12分鐘是在未來還是在過去。我希望我的應用程序只在所選時間至少5分鐘後才能繼續。

+2

刪除'abs()',如果結果是肯定的,它是過去。 –

+0

刪除abs()對輸出沒有任何影響。 – aqq

+0

刪除abs必須有所作爲,如果你得到否定的意思是在未來... – Salketer

回答

-1
$enteredDate = new DateTime($chosen_date)->getTimestamp(); 
$now = new DateTime()->getTimestamp(); 
if(($enteredDate-$now)/60 >=5)echo 'ok'; 

基本上,代碼從1970年1月1日起以秒爲單位轉換。我們計算兩個日期之間的差異,並根據我們想要的分鐘數將結果除以60。如果至少有5分鐘的差異,我們就可以。如果這個數字是負數,那麼我們就是過去了。

+0

這有一個問題。如果時間在未來,它會回顯'ok',但如果日期是未來,那麼我們假設下個月它不會回顯'ok'。 – aqq

+0

我已經改變了它,使用時間戳,而不是允許比較兩個大數字......我首先使用的DateDiff需要測試所有差異,而不僅僅是分鐘。 – Salketer

+0

請給你的答案添加一些解釋。 – kenorb

0

你正在做太多的工作。只要使用日期時間()做日期的功能爲您提供:

// Wrong way to do this. Work with timezones instead 
$cur_date = (new DateTime()->modify("+1 hours")); 

// Assuming acceptable format for $chosen_date 
$to_time = new DateTime($chosen_date); 

$diff = $cur_date->diff($to_time); 

if ($diff->format('%R') === '-') { 
    // in the past 
} 

echo $diff->format('%i') . ' minutes'; 

Demo

+0

此代碼無效。如果用戶輸入明天的完全相同的時間,它將只顯示0分鐘,而不是1440(一天中的分鐘數) – Salketer

+0

@Salketer他們的示例意味着這不是一個有效的場景 –

-1

如果有人正在做同樣的事情,我發現這是在默認情況下我使用的框架包括的碳庫(Laravel 5),做這個計算要容易得多。

$chosen_date = new Carbon($chosen_date, 'Europe/London'); 

    $whitelist_date = Carbon::now('Europe/London'); 
    $whitelist_date->addMinutes(10); 

    echo "Chosen date must be after this date: ".$whitelist_date ."</br>"; 
    echo "Chosen Date: ".$chosen_date ."</br>"; 

    if ($chosen_date->gt($whitelist_date)) { 

     echo "proceed"; 
    } else { 
     echo "dont proceed"; 
    } 
相關問題