Skip to content

Instantly share code, notes, and snippets.

@CodeNegar
Created September 13, 2012 11:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save CodeNegar/3713606 to your computer and use it in GitHub Desktop.
Save CodeNegar/3713606 to your computer and use it in GitHub Desktop.
php: fuzzy time ago
<?php
function prettyDate($date){
$time = strtotime($date);
$now = time();
$ago = $now - $time;
if($ago < 60){
$when = round($ago);
$s = ($when == 1)?"second":"seconds";
return "$when $s ago";
}elseif($ago < 3600){
$when = round($ago / 60);
$m = ($when == 1)?"minute":"minutes";
return "$when $m ago";
}elseif($ago >= 3600 && $ago < 86400){
$when = round($ago / 60 / 60);
$h = ($when == 1)?"hour":"hours";
return "$when $h ago";
}elseif($ago >= 86400 && $ago < 2629743.83){
$when = round($ago / 60 / 60 / 24);
$d = ($when == 1)?"day":"days";
return "$when $d ago";
}elseif($ago >= 2629743.83 && $ago < 31556926){
$when = round($ago / 60 / 60 / 24 / 30.4375);
$m = ($when == 1)?"month":"months";
return "$when $m ago";
}else{
$when = round($ago / 60 / 60 / 24 / 365);
$y = ($when == 1)?"year":"years";
return "$when $y ago";
}
}
echo prettyDate("2012-09-12 12:23:45")."<br />";
echo prettyDate("2012-09-13 05:25:45")."<br />";
echo prettyDate("2012-01-01 01:00:00")."<br />";
echo prettyDate("2001-05-30 00:00:00")."<br />";
?>
@sionleroux
Copy link

Won't this get more and more inaccurate as time passes, considering that months and years don't always have the same length?

@aletson
Copy link

aletson commented Aug 26, 2014

Fuzzy. :P It uses an average. Should be fine for estimating, which is what it's all about.

@shengjie
Copy link

I wrote a french version, can be used in twig extension :)

   public function date_fuzzy(\DateTime $date = null)
    {
        if($date==null) return "n/a";

        $time = $date->getTimestamp();
        $now = time();
        $ago = $now - $time;
        $unit = "";
        if ($ago < 60) {
            $value = round($ago);
            $unit = ($value == 1) ? "second" : "secondes";
        } elseif ($ago < 3600) {
            $value = round($ago / 60);
            $unit = ($value == 1) ? "minute" : "minutes";
        } elseif ($ago >= 3600 && $ago < 86400) {
            $value = round($ago / 60 / 60);
            $unit = ($value == 1) ? "heure" : "heures";
        } elseif ($ago >= 86400 && $ago < 2629743.83) {
            $value = round($ago / 60 / 60 / 24);
            $unit = ($value == 1) ? "jour" : "jours";
        } elseif ($ago >= 2629743.83 && $ago < 31556926) {
            $value = round($ago / 60 / 60 / 24 / 30.4375);
            $unit = ($value == 1) ? "mois" : "mois";
        } else {
            $value = round($ago / 60 / 60 / 24 / 365);
            $unit = ($value == 1) ? "an" : "ans";
        }
        return "Il y a $value $unit";
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment