<?php
function format($datetime) {
$now = time();
$created = strtotime($datetime);
// La différence est en seconde
$diff = $now-$created;
$m = ($diff)/(60); // on obtient des minutes
$h = ($diff)/(60*60); // ici des heures
$j = ($diff)/(60*60*24); // jours
$s = ($diff)/(60*60*24*7); // et semaines
var_dump($now, $created, $diff);
if ($diff < 60) { // "il y a x secondes"
return 'Il y a '.$diff.' secondes';
}
elseif ($m < 60) { // "il y a x minutes"
$minute = (floor($m) == 1) ? 'minute' : 'minutes';
return 'Il y a '.floor($m).' '.$minute;
}
elseif ($h < 24) { // " il y a x heures, x minutes"
$heure = (floor($h) <= 1) ? 'heure' : 'heures';
return 'Il y a '.floor($h).' '.$heure;
}
elseif ($j < 7) { // " il y a x jours, x heures"
$jour = (floor($j) <= 1) ? 'jour' : 'jours';
return 'Il y a '.floor($j).' '.$jour;
}
elseif ($s < 5) { // " il y a x semaines, x jours"
$semaine = (floor($s) <= 1) ? 'semaine' : 'semaines';
return 'Il y a '.floor($s).' '.$semaine;
}
else { // on affiche la date normalement
return strftime("%d %B %Y à %H:%M", $created);
}
}
echo date("c")."<br>";
echo format("2019-09-27 18:56:53")."<br>";
echo format("2019-10-04 14:56:53")."<br>";
echo format("2019-10-04 17:53:53")."<br>";
echo format("2018-10-04 17:53:53")."<br>";
echo format("2019-09-04 17:53:53")."<br>";
echo format("2001-10-04 17:53:53")."<br>";
echo format(time())."<br>";
testé sur
http://phptester.net/ donne :
2019-10-04T17:58:46-04:00
int(1570226326) int(1569625013) int(601313) Il y a 6 jours
int(1570226326) int(1570215413) int(10913) Il y a 3 heures
int(1570226326) int(1570226033) int(293) Il y a 4 minutes
int(1570226326) int(1538690033) int(31536293) 04 October 2018 à 17:53
int(1570226326) int(1567634033) int(2592293) Il y a 4 semaines
int(1570226326) int(1002232433) int(567993893) 04 October 2001 à 17:53
int(1570226326) bool(false) int(1570226326) 31 December 1969 à 19:00
on a un bool(false) pour $created quand le paramètre passé est time() d'où un résultat inattendu. avec d'autres valeurs, la fonction fonctionne.