PHP - 检查选择的时间是否至少为5分钟

时间:2015-09-22 16:54:53

标签: php validation datetime

在我正在处理的应用程序中,用户必须选择至少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,所选时间是2015年9月22日下午5:41 - 它会告诉我12分钟的差异。

我想知道的是我如何知道这12分钟是将来还是过去。我希望我的申请只有在选定的时间至少是未来5分钟后才能继续。

3 个答案:

答案 0 :(得分:0)

你做的太多了。只需使用DateTime()为您执行日期数学运算:

// 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

答案 1 :(得分:-1)

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

基本上,代码采用自1970年1月1日以来以秒为单位转换的两个日期。我们计算两个日期之间的差异,并将结果除以60,因为我们需要分钟。如果有至少5分钟的差异,我们没问题。如果数字是负数,那么我们就过去了。

答案 2 :(得分:-1)

如果有人想要做类似的事情,我发现默认包含我正在使用的框架(Laravel 5)的Carbon库,这个计算要容易得多。

  $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";
    }
相关问题