1

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?

Nyxynyx
  • 61,411
  • 155
  • 482
  • 830
  • possible duplicate of [How to express the difference between two dates in a human-readable format](http://stackoverflow.com/questions/6542931/how-to-express-the-difference-between-two-dates-in-a-human-readable-format) – JJJ Oct 18 '11 at 12:52
  • 3
    I love the first sentence. Is the idea that the funny video site is playing funny videos integral to the problem? :) – Alex Oct 18 '11 at 12:55
  • people seems to be downvoting alot these days – Nyxynyx Oct 19 '11 at 03:31
  • I assume this question was collecting dvs because it is a requirements dump. Saying that you found `strtotime()` and `new date()` doesn't really narrow the task down to a specific failure point. This requires answers to provide a fully built tutorial/solution that handles many different human-readable possibilities. AND your question is asking multiple questions. For such an old page with a common/basic title, this page has proven unhelpful to quite a lot of researchers and the accepted answer doesn't get close to delivering what you've asked for. **Needs More Focus** – mickmackusa Dec 02 '21 at 22:56

2 Answers2

9

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

Anonymous
  • 3,679
  • 6
  • 29
  • 40
2

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

0xCAFEBABE
  • 5,576
  • 5
  • 34
  • 59