【问题标题】:Get the difference between form $_POST date to new date获取表格 $_POST 日期与新日期之间的差异
【发布时间】:2015-04-09 07:45:26
【问题描述】:

我想获取 $_POST 时间和提交后页面内生成的时间之间的差异。

因为我想做一个 if 语句,如果两次之间的差异小于 5 秒,那么...否则...

使用 php date("H:i:s); 函数是否正确?

生成时间

<?php date = date("H:i:s"); ?>

隐藏表单域中的回显时间

<input name="tstmp" type="hidden" value="<?php echo $date; ?>"/>

然后在用户提交表单后被定向到的页面中。

//could the problem be this is a string within the $_POST
$timestart = $_POST['tstmp'];

$timeend = date("H:i:s");

//can this only be used with timestamp?
$interval = $timestart->diff($timeend);

【问题讨论】:

  • //can this only be used with timestamp? 不...但是,由于diff()DateTime 类的方法,它只能从该类的对象中调用。 date() 函数的结果是一个字符串!!!
  • 为什么不首先将 unix 时间戳值放入表单中? (如果您只使用H:i:s,我可以在明天或下周的这个时候再次发送相同的表格,这可能不是您想要的......)

标签: php validation datetime post spam-prevention


【解决方案1】:

获取您的时间戳并使用 strtotime() 将它们转换为 unix 时间戳并将它们彼此相减。

http://php.net/manual/en/function.strtotime.php

$timestart = $_POST['tstmp'];
$timeend =  date("H:i:s");

$timestart = strtotime($timestart);
$timeend   = strtotime($timeend);

if(($timeend - $timestart) > 5){
    echo 'TIME IS GREATER THAN 5 SECONDS';
}

【讨论】:

    【解决方案2】:

    将您输入的时间戳转换为日期时间对象

    $timeStart = new DateTime($timeStart);
    $timeEnd = new DateTime($timeEnd);
    

    已编辑:修复了清晨编码大脑无法正常工作的问题。

    【讨论】:

    • 这有什么帮助? $timeStart 仍然是 string...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 2020-03-22
    • 2017-03-27
    • 2016-06-22
    • 2015-10-04
    • 1970-01-01
    相关资源
    最近更新 更多