【问题标题】:PHP - Check if chosen time is at least 5 minutes into the futurePHP - 检查选择的时间是否在未来至少 5 分钟
【发布时间】:2015-09-22 16:54:52
【问题描述】:

在我正在处理的应用程序中,用户必须选择至少 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 分钟后继续进行。

【问题讨论】:

  • 删除abs(),如果结果是肯定的,那就是过去了。
  • 删除 abs() 恐怕对输出没有影响。
  • 去除腹肌必须有所作为,如果你得到否定意味着未来......

标签: php validation datetime


【解决方案1】:

你做的太多了。只需使用 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

【讨论】:

  • 此代码无效。如果用户输入明天完全相同的时间,它只会显示 0 分钟,而不是 1440(一天中的分钟数)
  • @Salketer 他们的例子暗示这不是一个有效的场景
【解决方案2】:
$enteredDate = new DateTime($chosen_date)->getTimestamp();
$now = new DateTime()->getTimestamp();
if(($enteredDate-$now)/60 >=5)echo 'ok';

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

【讨论】:

  • 这个有问题。如果时间在未来,它会回显“确定”,但如果日期在未来,比如说下个月,那么它不会回显“确定”。
  • 我已经改变了它,使用时间戳代替将允许比较 2 个大数字...我首先使用的 DateDiff 需要测试所有差异,而不仅仅是分钟。
  • 请在您的回答中添加一些解释。
【解决方案3】:

如果有人想做类似的事情,我发现默认情况下包含在我使用的框架 (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";
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 1970-01-01
    • 1970-01-01
    • 2013-02-21
    • 2012-04-11
    相关资源
    最近更新 更多