Timestamp as " X Days Ago", can't modify script correctly

I have a todo list app I'm working on. It displays the timestamp from when a todo was created and even allows the user to choose what the format should be.

In this snippet, the code grabs info from a mySQL db to see how to format the date:

public function __toString(){
    // The string we return is outputted by the echo statement

    if ( $this->data['date_created'] == '') {
        $date_created =  date($GLOBALS["config"]["date_format"].' '.$GLOBALS["config"]["time_format"]);
    }
    else 
        $date_created = date($GLOBALS["config"]["date_format"].' '.$GLOBALS["config"]["time_format"], strtotime($this->data['date_created']));

(It's pulling from a row called date_format and a row called time_format)

I'm trying to implement this code:

function relativeTime($dt,$precision=2) {
    if(is_string($dt)) $dt = strtotime($dt);

    $times=array(   365*24*60*60    => "year",
                    30*24*60*60     => "month",
                    7*24*60*60      => "week",
                    24*60*60        => "day",
                    60*60           => "hour",
                    60              => "minute",
                    1               => "second");

    $passed=time()-$dt;

    if($passed<5)
    {
        $output='less than 5 seconds ago';
    }
    else
    {
        $output=array();
        $exit=0;

        foreach($times as $period=>$name)
        {
            if($exit>=$precision || ($exit>0 && $period<60)) break;

            $result = floor($passed/$period);
            if($result>0)
            {
                $output[]=$result.' '.$name.($result==1?'':'s');
                $passed-=$result*$period;
                $exit++;
            }
            else if($exit>0) $exit++;
        }

        $output=implode(' and ',$output).' ago';
    }

    return $output;
}

I replaced $dt with $date_created and tried different combos, but I can't seem to get it right. I have a frontend error telling me that relativetime is undefined (it doesn't say relativeTime in error message, it has a lowercase "t"). What can I do to get $date_created to show up in the "Days ago" format? Thanks!

Answers


I would rewrite this completely as something like this:

$times = array(365*24*60*60    => "year",
               30*24*60*60     => "month",
               7*24*60*60      => "week",
               24*60*60        => "day",
               60*60           => "hour",
               60              => "minute",
               1               => "second");

$passed = time() - $dt;

if ($passed < 5) {
    echo "Less than 5 seconds ago.";
} else {
    foreach ($times as $period => $name) {
        if ($passed >= $period) {
            echo round($passed / $period) . " " . $name . "(s) ago";
            break;
        }
    }
}

See this link for an example (I've hardcoded the value of $passed for testing purposes; you can edit the value to see how it affects things):

http://ideone.com/e8KXK


As an aside, I've realized that I think your original solution attempts to fully account for every second that has passed. This is a bad idea from a user experience perspective. I don't think many users will want to see "Created 1 year and 7 months and 19 days and 4 hours and 36 minutes and 28 seconds ago", which is the type of result that your original code was shooting for. This answer will only display the largest unit.


Use this functions for dates in the future or passed dates.

function relativeTime($dt,$precision=2) {
        if(is_string($dt)) $dt = strtotime($dt);
        $times = array(365*24*60*60    => "year",
                   30*24*60*60     => "month",
                   7*24*60*60      => "week",
                   24*60*60        => "day",
                   60*60           => "hour",
                   60              => "minute",
                   1               => "second");

        $passed = abs(time() - $dt);

        if ($passed < 5) {
            echo "Less than 5 seconds ago.";
        } else {
            foreach ($times as $period => $name) {
                if ($passed >= $period) {
                    $value = round($passed / $period);
                    $nameReal = $name;
                    if($value != 1) $nameReal .= "s";

                    if(time() > $dt)
                        echo  $value . " " . $nameReal . " ago";
                    else
                        echo "In ". $value . " " . $nameReal;
                    break;
                }
            }
        }
    }

Need Your Help

What datatype should I use to store long encrypted messages on MySQL?

php mysql encryption blob

I am working on an web application that will allow users to write messages and store them on a database to be accessed by some other users who are meant to. I have a user authentication system read...

WebBrowser.InvokeScript() Throws Error: 80020006

c# javascript windows-phone-8 webbrowser-control

I am developing a Windows Phone 8 App and i am new to Windows Phone 8.