i want a php function to convert a unix time stamp to like this:
15 seconds
or
45 minutes
or
3 hours
and not like this : 2sec
Try this:
function toFriendlyTime($seconds) {
$measures = array(
'day'=>24*60*60,
'hour'=>60*60,
'minute'=>60,
'second'=>1,
);
foreach ($measures as $label=>$amount) {
if ($seconds >= $amount) {
$howMany = floor($seconds / $amount);
return $howMany." ".$label.($howMany > 1 ? "s" : "");
}
}
return "now";
}
As you can see, it's also flexible for adding/removing measures of time as you see fit. Just be sure to order the measures from largest to smallest. A test:
print(
toFriendlyTime(0)."\n"
.toFriendlyTime(1)."\n"
.toFriendlyTime(2)."\n"
.toFriendlyTime(60)."\n"
.toFriendlyTime(3600)."\n"
.toFriendlyTime(24*3600)."\n"
);
Results in:
now
1 second
2 seconds
1 minute
1 hour
1 day