Time difference between a Date and current Time?

2019-08-01 04:30发布

问题:

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.