I have a page where someone leaves a comment now I want it to say like

X said 1 Hour ago or X said 25 minutes ago or if passed 24hrs, X said 2 days ago.

How can i go by doing this?

    function time_passed($since_ts)
    {
        $periods = array('years' => 0, 'months' => 0, 'weeks' => 0, 'days' => 0, 
                         'hours' => 0, 'minutes' => 0, 'seconds' => 0);
        $current_ts = time();
        foreach ($periods as $key => $val) {
            while (($ts = strtotime('-1 ' . $key, $current_ts)) > $since_ts) {
                $periods[$key]++;
                $current_ts = $ts;
            }
        }
        return $periods;
    }

      so i pass in time in seconds?

      so i passed in seconds for [date] => 2009-01-19 12:23:46
      from NOW(); at the time it was 4660 seconds

      so i passed it and got

      Array
      (
      [years] => 39
      [months] => 0
      [weeks] => 2
      [days] => 4
      [hours] => 17
      [minutes] => 21
      [seconds] => 43
      )

        You pass in a timestamp (that's what the "ts" in "$since_ts" stands for). Like this:

        $arr = time_passed(strtotime('2009-01-19 12:23:46'));
        echo 'Hal said ';
        foreach ($arr as $key => $val) {
            if (!$val) {
                continue;
            } else {
                echo $val . ' ' . $key . ' ';
            }
        }
        echo ' ago';

        Output:

        Hal said 26 minutes 35 seconds ago
          2 months later

          hey installer im having issue with this code. it tends to crash my site when all comments that were left this passed saturday march 7th (daylight savings). trying figure it out any clue?

            OKAY i fixed it, incase yourself or anyone else
            i put "GMT" in

            while (($ts = strtotime('-1 ' . $key . " GMT", $current_ts)) > $since_ts) {

              5 days later

              NM its not fixed.

              im gettin odd results

              while (($ts = strtotime('-1 ' . $key . " GMT", $current_ts)) > $since_ts) {

              has to be

              while (($ts = strtotime('-1 ' . $key, $current_ts . " GMT")) > $since_ts) {

              but im not getting correct results anyone have any clue this day light savings time is causing that line to crash.

                Write a Reply...