我一直在尝试这一点,并且不能让该死的代码工作..这是我的第一篇文章,我经历了一些,尝试了一百万种不同的方式..我只是想得到几小时的差异,然后我就定了,我会把其余的想出来......
现在,它给了我不寻常的答案(说有两个小时的差异,它会给我14个作为答案)原谅我的编码,我多年没有这样做,没有真正的正规训练。在我的评论中,我会尽可能地彻底,并且感谢很多。任何链接赞赏。我尝试了很多。使用PHP 5.3.something,并取消了Wordpress 3.7.1数据库。
提前感谢初学者的帮助。我想显示“更新x小时前”。一旦我的darned东西显示正确的结果,我会把剩下的东西拿出来。
//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);
答案 0 :(得分:3)
您可以大幅简化代码。我建议重构它以使用DateTime
,特别是DateTime::diff()
。
$now = new DateTime();
$post = new DateTime($row2['post_date']);
$interval = $now->diff($post);
echo "Updated " . $interval->h . " hours ago";
请注意,这只会显示最多24小时的差异。如果您想显示所有小时数,即使差异超过24小时,您也需要计算时间。像这样:
$hours = $interval->h + ($interval->format("%a") * 24);
echo "Updated $hours hours ago";
答案 1 :(得分:1)
如果你只是试图获得两个任意时间之间的小时数,最简单的方法是获得两次的秒数差异,然后除以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 function human_time_diff()
。
示例:
<?php echo human_time_diff( get_the_time('U'), current_time('timestamp') ) . ' ago';
结果:
2 days ago.
答案 2 :(得分:0)