0

I have two dates variable in php

$var1 and $var2

var1 contains some past time and var2 contains current time.I want to calculate the relative time such as 3 hrs ago,5 day ago etc

I have been stucked in this from quite a while.can anyone pls help

I already referred to the existing stackoverflow posts regarding this but it didn't help me.

user3318980
  • 39
  • 2
  • 7

2 Answers2

0

you can calculate difference and then convert to natural language. And try to use Search field on StackOverflow next time ;)

Community
  • 1
  • 1
Pirozek
  • 1,250
  • 4
  • 16
  • 25
0

Here's a function I wrote a while back to do exactly that:

function relative_date($timestamp) {
    // calculate time difference
    $timediff = time() - $timestamp;
    switch($timediff) {
        // less than a minute, show seconds
        case $timediff <= 60:
            $seconds = $timediff;
            $str = $timediff . ($timediff == 1 ? " second ago" : " seconds ago");
            break;
        // less than a hour, show minutes
        case $timediff <= 3600:
            $minutes = floor($timediff / 60);
            $str = $minutes . ($minutes == 1 ? " minute ago" : " minutes ago");
            break;
        // less than a day, show hours
        case $timediff <= 86400:
            $hours = floor($timediff / 3600);
            $str = $hours . ($hours == 1 ? " hour ago" : " hours ago");
            break;
        // less than a year, show days
        case $timediff <= (86400 * 365):
            $days = floor($timediff / 86400);
            $str = $days . ($days == 1 ? " day ago" : " days ago");
            break;
        // over a year, just show years
        default:
            $years = floor($timediff / (86400 * 365));
            $str = $years . ($years == 1 ? " year ago" : " years ago");
    }
    return $str;
}
The Blue Dog
  • 2,475
  • 3
  • 19
  • 25
  • @Ing.MichalHudak: Copy and paste comment, was it? Where does this function show months? Maybe you should read what's in front of you before you blindly comment and downvote. – The Blue Dog Jun 01 '14 at 10:07