There is some issue with some language display time ago for example in Arabic there 3 needed formats to display date.
I use this functions in my projects hopefully they can help someone (any suggestion or improvement I'll be apperciate :) )
/**
*
* @param string $date1
* @param string $date2 the date that you want to compare with $date1
* @param int $level
* @param bool $absolute
*/
function app_date_diff( $date1, $date2, $level = 3, $absolute = false ) {
$date1 = date_create($date1);
$date2 = date_create($date2);
$diff = date_diff( $date1, $date2, $absolute );
$d = [
'invert' => $diff->invert
];
$diffs = [
'y' => $diff->y,
'm' => $diff->m,
'd' => $diff->d
];
$level_reached = 0;
foreach($diffs as $k=>$v) {
if($level_reached >= $level) {
break;
}
if($v > 0) {
$d[$k] = $v;
$level_reached++;
}
}
return $d;
}
/**
*
*/
function date_timestring( $periods, $format = 'latin', $separator = ',' ) {
$formats = [
'latin' => [
'y' => ['year','years'],
'm' => ['month','months'],
'd' => ['day','days']
],
'arabic' => [
'y' => ['سنة','سنتين','سنوات'],
'm' => ['شهر','شهرين','شهور'],
'd' => ['يوم','يومين','أيام']
]
];
$formats = $formats[$format];
$string = [];
foreach($periods as $period=>$value) {
if(!isset($formats[$period])) {
continue;
}
$string[$period] = $value.' ';
if($format == 'arabic') {
if($value == 2) {
$string[$period] = $formats[$period][1];
}elseif($value > 2 && $value <= 10) {
$string[$period] .= $formats[$period][2];
}else{
$string[$period] .= $formats[$period][0];
}
}elseif($format == 'latin') {
$string[$period] .= ($value > 1) ? $formats[$period][1] : $formats[$period][0];
}
}
return implode($separator, $string);
}
function timeago( $date ) {
$today = date('Y-m-d h:i:s');
$diff = app_date_diff($date,$today,2);
if($diff['invert'] == 1) {
return '';
}
unset($diff[0]);
$date_timestring = date_timestring($diff,'latin');
return 'About '.$date_timestring;
}
$date1 = date('Y-m-d');
$date2 = '2018-05-14';
$diff = timeago($date2);
echo $diff;