-1

I have a simple function below that gets seconds and returns it like "2 minutes ago", "9 hours ago" etc...

if I pass 1 on 'relativedate()' function it will just return 1 sec and so on. As we all know 60*60*24*7*30 or 18144000sec = 1 month. Therefore if I pass a value of 18144000 on the parameter, it should return 1 month.However, if I pass a value on the parameter lets say 231440000 on relativedate() which should be more than a year, it is returning '13 months' instead of 1 year.

function relativedate($secs) {
        $second = 1;
        $minute = 60;
        $hour = 60*60;
        $day = 60*60*24;
        $week = 60*60*24*7;
        $month = 60*60*24*7*30;
        $year = 60*60*24*7*30*365;

        if ($secs <= 0) { $output = "now";
        }elseif ($secs > $second && $secs < $minute) { $output = round($secs/$second)." second";
        }elseif ($secs >= $minute && $secs < $hour) { $output = round($secs/$minute)." minute";
        }elseif ($secs >= $hour && $secs < $day) { $output = round($secs/$hour)." hour";
        }elseif ($secs >= $day && $secs < $week) { $output = round($secs/$day)." day";
        }elseif ($secs >= $week && $secs < $month) { $output = round($secs/$week)." week";
        }elseif ($secs >= $month && $secs < $year) { $output = round($secs/$month)." month";
        }elseif ($secs >= $year && $secs < $year*10) { $output = round($secs/$year)." year";
        }else{ $output = " more than a decade ago"; }

        if ($output <> "now"){
            $output = (substr($output,0,2)<>"1 ") ? $output."s" : $output;
        }
        return $output;
    }



echo relativedate(60); // 1 minute
user1995927
  • 313
  • 1
  • 3
  • 11
  • 1
    why dont you split and check with >= 12 (beware for the next step too..means 26 months should be 2 years and 2months so you need to iterate over thr as well...just a check what about LEAP year counting ..code for that as well while handling dates/time) – swapnesh Mar 17 '13 at 08:47
  • 1
    Your year calculation is for 365 Months, not 12 months – Toby Allen Mar 17 '13 at 08:48
  • http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/501415#501415 – Toby Allen Mar 17 '13 at 08:48

1 Answers1

0

Your year calculation is for 365 Months, not 12 months

Toby Allen
  • 10,997
  • 11
  • 73
  • 124