【问题标题】:Get total time difference between two dates using php [duplicate]使用php获取两个日期之间的总时间差[重复]
【发布时间】:2012-05-28 15:02:23
【问题描述】:

可能重复:
How to calculate the difference between two dates using PHP?

这里我提到了两次它的日期

2008-12-13 10:42:00

2010-10-20 08:10:00

我想得到 (h:m:s) 格式的总时差

【问题讨论】:

  • 只需检查@tarion 链接的问题,并使用投票最多(未接受)的答案,使用日期时间的差异:php.net/manual/en/datetime.diff.php
  • -1。如果你用谷歌搜索“两个日期之间的 php 差异”,那么 Tarion 链接的确切副本就是第一个结果。
  • 这不是链接到的问题的副本,事实上我发现这个答案更有帮助......我们可以从这个问题中删除重复项吗?

标签: php


【解决方案1】:

您可以使用strtotime function 将时间转换为整数并减去它们。

$time1 = strtotime("2008-12-13 10:42:00");
$time2 = strtotime("2010-10-20 08:10:00");

$diff = $time2-$time1;
// the difference in int. then you can divide by 60,60,24 and 
// so on to get the h:m:s out of it

【讨论】:

  • 感谢大家的宝贵重播
【解决方案2】:

如果您正在使用或能够使用 PHP 5.3.x 或更高版本,则可以使用其 DateTime 对象功能:

$date_a = new DateTime('2010-10-20 08:10:00');
$date_b = new DateTime('2008-12-13 10:42:00');

$interval = date_diff($date_a,$date_b);

echo $interval->format('%h:%i:%s');

您可以通过多种方式使用该格式,一旦您在 DateTime 对象中有日期,您就可以利用许多不同的功能,例如通过普通运算符进行比较。更多信息请参见手册:http://us3.php.net/manual/en/datetime.diff.php

【讨论】:

  • 感谢大家的宝贵重播
  • 其实上面是PHP 5.3.x或更高版本
  • 你说得对,我认为这是一个(非常古老的)错字。已更新,谢谢!
  • 如果我想要 diff 是正数还是负数,它只会给出区别
  • 可以使用“%R”格式字符串来表示是正区间还是负区间;有关格式选项的完整列表,请参阅 php.net/manual/en/dateinterval.format.php
【解决方案3】:

我在用什么:

$seconds = strtotime("2010-10-20 08:10:00") - strtotime("2008-12-13 10:42:00");

$days    = floor($seconds / 86400);
$hours   = floor(($seconds - ($days * 86400)) / 3600);
$minutes = floor(($seconds - ($days * 86400) - ($hours * 3600))/60);
$seconds = floor(($seconds - ($days * 86400) - ($hours * 3600) - ($minutes*60)));

您现在可以按照自己的方式进行格式化

【讨论】:

  • 感谢大家的宝贵重播。在以上代码的帮助下,我得到了答案 $seconds = strtotime("2000-03-01 10:02:00") - strtotime("2000 -02-28 10:02:00"); $days = floor($seconds / 86400); $hours = floor(($seconds - ($days * 86400)) / 3600); $minutes = floor(($seconds - ($days * 86400) - ($hours * 3600))/60); $seconds = floor(($seconds - ($days * 86400) - ($hours * 3600) - ($minutes*60)));$ff=$days*24;echo $time = $ff+$hours。”小时".$minutes."minutes".$seconds."seconds";
  • "楼层($seconds / 86400);"除非在日期中特别添加时间,否则将在“夏令时”日期失败。否则它将休息 1 小时,并且发现日期的数量将太少 1 天(因为它短 1 小时)。请改用 DateTime 和 date_diff
猜你喜欢
  • 2010-12-18
  • 1970-01-01
  • 1970-01-01
  • 2013-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多