【问题标题】:Trouble getting age in hours难以以小时为单位计算年龄
【发布时间】:2011-02-25 19:18:11
【问题描述】:

我正在尝试以小时为单位计算某物的年龄。

$data['record'] 是 DATETIME 字段中的 mysql NOW() 时间戳。

$data['record'] 已经 20 分钟了,当我这样做的时候:

$minutes= date('i',(strtotime("now")-strtotime($data['record'])));

$minutes 正确返回 20,但是由于某种原因,当我尝试 $hours 时,它返回 '5'。

$hours = date('g',(strtotime("now")-strtotime($data['record'])));

这没有意义,因为 $hours 应该返回 0,因为记录不到 60 分钟...

当我检查 "strtotime("now")-strtotime($data['record'])" 的值时,它等于 '980'。救命!

【问题讨论】:

    标签: php mysql datetime date time


    【解决方案1】:

    请比较php中strtotime("now")和sql中select now();的输出。我认为这里隐藏了一个时区问题。

    如您所说,strtotime("now")-strtotime($data['record']) 返回 980,应该以分钟为单位。 960 可除以 60 并在 16 小时出现,因此 980 是 16 小时 20 分钟 - 20 分钟正是您要寻找的。您需要调整任一实例以使用另一个实例的时间 - 我会始终使用 UTC。如需显示,请适当解析并输出当地时间。

    【讨论】:

      【解决方案2】:

      请看:http://php.net/manual/en/function.date.php

      当$format参数=“g”时,返回值1-12。

      【讨论】:

        【解决方案3】:

        Date 不会像您期望的那样工作。

        日期采用时间戳(自 Unix 纪元(格林威治标准时间 1970 年 1 月 1 日 00:00:00)以来的秒数),并将其转换为清晰的时间格式。本质上,如果值为 980,您将在午夜 + 980 秒(大约 1970 年 1 月 1 日 00:16:20 GMT。当您转换时区差异时,(机会是,大约 5 小时差异)这样你就得到了五个。

        要解决这个问题,只需取 980,然后除以 60 得到分钟,然后再除以 60 得到小时,所以:

        $hours = ((strtotime("now")-strtotime($data['record'])) / 60) / 60;
        

        不需要date,因为您需要的是相对时间,而不是绝对时间。

        【讨论】:

        • @John 没问题,如果您需要其他任何东西,请告诉我们。
        猜你喜欢
        • 2011-06-10
        • 2012-11-12
        • 1970-01-01
        • 2015-05-21
        • 1970-01-01
        • 1970-01-01
        • 2018-08-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多