Time difference between a Date and current Time?

北城余情 提交于 2020-01-15 09:05:10

问题


Assume I have a funny video site that shows funny videos to users. Below every video, I want to have a statement that says "5 seconds ago", "31 minutes ago", "Yesterday", "2 days ago" based on a timestamp of the video and the current time.

The timestamp that I have is in the format: 2011-10-17 07:08:00.

I'm not too good with dates, but I'm guessing that I need to find the difference between the 2 date/time in seconds, then decide if its between 0sec & 60sec to display in seconds, or between 60sec & 3600sec to display in minutes, or between 3600sec & 3600x24sec to display in hours, between 3600x24sec & 3600x24x2sec to display yesterday, and so on... I believe I should be using strtotime() but I cant seem to find the current time as those solutions I found used new date() which does not seem to work!

How can I do this?

Btw, side question, when I insert 2011-10-17, 7:08PM EDT into a MySQL timestamp column, it gets converted to 2011-10-17 07:08:00 which is AM. How can I get it to be stored in the correct AM/PM?


回答1:


You can use the DateTime functions of php.

$datetime1 = new DateTime('2011-10-17 07:08:00');
$datetime2 = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

From here on you can use some if-statements to output the time difference in another format (seconds, minutes, hours, month, etc.) depending on the actual time difference! The formats for the output are to find here




回答2:


You can very easily use the DATEDIFF and TIMEDIFF functions of MySQL. Both together tell you exactly how much time has passed.



来源:https://stackoverflow.com/questions/7807241/time-difference-between-a-date-and-current-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!