ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

PHP-计算时间差(日期时间)时的strtotime和怪异结果

2019-10-30 04:39:23  阅读:257  来源: 互联网

标签:strtotime wordpress mysql php


我已经尝试了一段时间,无法使该死的代码正常工作..这是我的第一篇文章,我经历了一些尝试,尝试了一百万种不同的方法.以小时为单位,然后我开始工作,剩下的我会解决的.

现在,它给了我不寻常的答案(例如,相差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

标签:strtotime,wordpress,mysql,php
来源: https://codeday.me/bug/20191030/1965507.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有