【问题标题】:Calculate total hours between 2 time stamps计算 2 个时间戳之间的总小时数
【发布时间】:2011-11-09 07:05:00
【问题描述】:

我有两个变量:

$start_time = '9:36';
$end_time = '12:47';

我将如何计算两次之间的小时数并将它们存储在这样的变量中:

$total_hours = 3;

我读到您需要先转换时间。也不需要日期,因为这都是在同一天。

任何帮助将不胜感激

【问题讨论】:

标签: php function


【解决方案1】:

如果您只需要计算小时差异,您可以使用 datetime class 特别是函数 date_parse_from_format,您只需提供格式作为种子,然后您需要解析的内容给出计算差异

编辑 1

你可以用更少的开销做一些事情:

$start_time = '9:36';
$end_time = '12:47';
$today = date('Y-d-m');
$start = strtotime($today . ' ' . $start_time);
$end = strtotime($today . ' ' . $end_time);

$diff = floor(($end - $start) / 3600);

// or if you don't need the exact hours

$diff = ($end - $start) / 3600;

【讨论】:

    【解决方案2】:
    1. 将时间字符串转换为时间戳:strftime
    2. 拿差价,然后
    3. 一个。使用 date 获取小时 (H) 值
      湾。除以 3600 并四舍五入与您一样多的数字 需要

    $total_hours = (int)date('G', abs(strtotime($time2)-strtotime($time1)));

    【讨论】:

    • 它可以工作,除了在小时前留下零,像这样:“03”。见this codepad
    • @Tadeck:要保留前导零,请在 date 中使用 G 而不是 Hdate('G', abs(strtotime($time2)-strtotime($time1)));。如果输入更详细的时间,则此方法有效,例如:10:23:43 GMT,因为strftime 可以完成这项工作
    • @netmano:所以你的解决方案应该是date('G', abs(strtotime($time2)-strtotime($time1)));,而不是你给出的那个。或者甚至应该是:$total_hours = (int)date('G', abs(strtotime($time2)-strtotime($time1)));,你不觉得吗?
    • @Tadeck:是的,我错过了编辑功能,所以我写信给 commeny,顺便说一句,现在我在答案中更正了。谢谢!而如果使用(int)强制转换,H就没有问题了,因为03会被强制转换为3作为int。
    • @netmano:是的,如果进行强制转换,结果没有区别。但是为了与不同的语言保持一致,必须在将033 转换为整数之间进行选择,我会选择后者。在其他语言 (such as eg. JavaScript) 中,数字字符串中第一个位置的零很重要。
    【解决方案3】:

    见下文

    $start_time = '9:36';
    $end_time = '12:47';
    
    $v =  strtotime($end_time) - strtotime($start_time);
    echo date("h:i", $v);
    

    输出

     03:11
    

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

    【讨论】:

    • 需要date_default_timezone_set("UTC"); 以避免时区问题。
    【解决方案4】:

    这解决了你的问题:

    $start = explode(':', $start_time);
    $end = explode(':', $end_time);
    $total_hours = $end[0] - $start[0] - ($end[1] < $start[1]);
    

    请参阅this codepad 以获得证明。

    此解决方案假定两个小时都来自同一天。

    【讨论】:

    • 嗨,我知道你是如何使用爆炸功能的。有用。我从结束日期中减去开始日期。小时出来很好,但它总是错误地计算分钟。谢谢
    • @SebastianOpperman:没问题。只要知道如果开始和结束日期不同,这个解决方案将无法正常工作,您将不得不对其进行调整。祝你好运。
    • 只是个愚蠢的问题,假设 10 - (true) 可以安全地假设它总是与 (10 - 1) 相同吗?
    • 嗨@Tadeck,我尝试了你的解决方案,但它并没有真正起作用我使用的是 24 小时格式,这是结果codepad.org/SxpWzo8A,但它甚至不适用于 am/pm因为也许我们不知道它是否是上午/下午?你能帮忙吗?
    【解决方案5】:

    你们为什么要把事情搞得这么复杂?可以在一行代码中完成:

    abs((strtotime("11:00 AM") - strtotime("12:00 PM")) / 3600)
    

    结果:

    1
    

    请注意,这假定两个时间都在同一天,但如果两个时间来自不同日期,它仍然有效。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-14
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2020-06-28
      • 2021-01-03
      相关资源
      最近更新 更多