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!
I would rewrite this completely as something like this:
See this link for an example (I’ve hardcoded the value of
$passedfor 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.