【问题标题】:PHP : calculate day difference between stored datetime in mysql and current datetime for token expiryPHP:计算 mysql 中存储的日期时间与令牌到期的当前日期时间之间的天差
【发布时间】:2015-03-08 13:40:45
【问题描述】:

我将令牌创建时间存储到 mysql datetime

$date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
$datetime = $date->format('d-m-Y H:i:s');

然后在检查令牌到期时,我想查看令牌是否超过 20 天。可能,PHP 中的diff() 会这样做,但我如何计算天数差异?或者有没有更好的方法?

编辑

当我在 mysql 中插入 $datetime 时,PHP 正在插入 0000-00-00 00:00:00 。为什么? 我也试过strtotime($datetime)

【问题讨论】:

    标签: php mysql datetime


    【解决方案1】:

    DateTime 对象的diff() 方法返回DateInterval 的实例,它有一个名为days 的属性,这正是您想要的:

    $date = new DateTime('now', new DateTimeZone('Asia/Kolkata'));
    $diff = $date->diff($otherDate);
    if ($diff->days > 20) {
        // token expired, error...
    }
    

    【讨论】:

    • @InsaneCoder MySQL 的日期时间格式是 YYYY-mm-dd 而不是 dd-mm-YYYY。试试$date->format('Y-m-d H:i:s')
    • 不,我仍然得到全 0
    • @InsaneCoder 也许你应该把它作为一个单独的问题发布。 0000-00-00 00:00:00 只是意味着您传递了一个无效的值。但是如果没有实际查询的代码,就很难说出原因。
    猜你喜欢
    • 2019-01-24
    • 2016-06-22
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 2012-06-10
    相关资源
    最近更新 更多