strtotime和计算时差(datetime)时的奇怪结果


strtotime and weird results when calculating time differences (datetime)

我已经尝试了一段时间,但无法让该死的代码工作。。这是我的第一篇帖子,我已经经历了一些,尝试了一百万种不同的方式。。我只想得到小时的差额,然后我就做好了,我会把剩下的都弄清楚的。。

现在,它给了我不同寻常的答案(假设有2个小时的差异,它会给我14个答案)请原谅我的编码,我已经多年没有这样做了,也没有受过真正的正式培训。我会在评论中尽可能详尽,非常感谢。感谢任何链接。我已经尝试了很多。使用PHP 5.3.something,我完成了Wordpress 3.7.1数据库。

提前感谢您对初学者的帮助。我想显示"x小时前更新"。一旦我让该死的东西显示出正确的结果,我就会解决剩下的问题。

//This is the current date, putting it into strtotime so everything is in the same format. It displays accurately.
$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDateHour = date("H", strtotime($currentDate . $currentTime));
// This is the date I'm pulling from the database, it only displays
// when in strtotime for some reason. It displays accurately to what is in the mySQL DB
$upDate = date("Y-m-d H", strtotime($row2[post_date]));

// Some variables to make life easier for later if statements if I ever get that far. Displays accurately. 
$upDatehour = date("H", strtotime($row2[post_date]));
// trying simple subtraction
$hour = $currentDateHour - upDatehour;
// this is where the result is incorrect, what is wrong here? Any method I've tried gives me the same result, with or without strotime.. it's gotta be something simple, always is!
print strtotime($hour);

您可以极大地简化代码。我建议将其重构为使用DateTime,特别是DateTime::diff()

$now = new DateTime();
$post = new DateTime($row2['post_date']);
$interval = $now->diff($post);
echo "Updated " . $interval->h . " hours ago";

工作示例:http://3v4l.org/23AL6

请注意,这将只显示长达24小时的差异。如果你想显示所有时间,即使相差超过24小时,你也需要计算天数。类似这样的东西:

$hours = $interval->h + ($interval->format("%a") * 24);
echo "Updated $hours hours ago";

工作示例:http://3v4l.org/ilItU

如果您只是想获得两个任意时间之间的小时数,最简单的方法是获得两个时间的秒差,然后除以3600来确定两个日期之间的小时数来。

以下是一个基本示例:

<?php
$row2['post_date'] = '2013-12-02 07:45:38';  // date from database
$now = time();  // get current timestamp in seconds
$upDate = strtotime($row2['post_date']);  // convert date string to timestamp
$diff = $now - $upDate;   // subtract difference between the two times
$hours = floor($diff / 3600);  // get the number of hours passed between the 2 times
echo $hours; // display result

此外,Wordpress有一个内置的函数,它最终可能会实现您的最终目标,请参阅Wordpress函数human_time_diff()

示例:

<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';

结果:

2 days ago.

如何获得以小时为单位的日期差异示例:

$diff = date_diff(date_create(), date_create($row2['post_date']));
$hours = $diff->days * 24 + $diff->h;

如果您希望用前导零格式化输出数字,可以使用sprintf()str_pad()函数。sprintf()用于HH:mm格式的示例:

echo sprintf('%02d:%02d', $hours, $diff->i);

演示