user836910
user836910

Reputation: 484

converting php mysql time to seconds ago

im having a problem converting time. for some reason it seems to be defaulting back to 1970 which i believe is unix default time. im using this code, when i run the program i get 42years instead of 2 years. what am i missing. please help here is the code

<?php

  function convertime($ptime) {
        $etime = time() - $ptime;

        if($etime < 60) {
                return 'less than minute ag';
        }

        $a = array(12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute' //  1                       =>  'second'
                );

        foreach($a as $secs => $str) {
                $d = $etime / $secs;
                if($d >= 1) {
                        $r = round($d);
                        return $r . ' ' . $str . ($r > 1 ? 's' : '');
                }
        }
  }

?>

<?php

  $ctime = 2009-02-23 10:09:00 //time from mysql
        echo convertime($ctime);

?>

Upvotes: 1

Views: 1364

Answers (2)

Dzoki
Dzoki

Reputation: 739

<?php

  function convertime($ptime) {
        $etime = time() - $ptime;

        if($etime < 60) {
                return 'less than minute ag';
        }

        $a = array(12 * 30 * 24 * 60 * 60 => 'year', 30 * 24 * 60 * 60 => 'month', 24 * 60 * 60 => 'day', 60 * 60 => 'hour', 60 => 'minute' //  1                       =>  'second'
                );

        foreach($a as $secs => $str) {
                $d = $etime / $secs;
                if($d >= 1) {
                        $r = round($d);
                        return $r . ' ' . $str . ($r > 1 ? 's' : '');
                }
        }
  }

?>

<?php

  $ctime = strtotime('2009-02-23 10:09:00'); //time from mysql
  echo convertime($ctime);

?>

try it

Upvotes: 1

Jared Farrish
Jared Farrish

Reputation: 49238

Wrap strtotime() around your timestamp:

$ctime = strtotime('2009-02-23 10:09:00'); //time from mysql

http://codepad.org/HWQrLwBy

You need to compare a timestamp to a timestamp.

Upvotes: 2

Related Questions