1

With the help of Stackoverflow (Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...) I found out how to convert a timestamp to time ago format in PHP. In the current solution the plurality is defined as + 's' (which is fine in English)... but what to do if you want to change this logic manually for each time unit (because for some languages this logic is not effective)? So for example in Dutch year = jaar and years = jaren, month = maand and months = maanden, week = week and weeks = weken.

    function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );

    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}
Yoorizz
  • 217
  • 2
  • 12

1 Answers1

1

Here is a version of that function which uses an array for each period to indicate the word to use for singular and plural periods:

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $periods = array(
        'y' => ['jaar', 'jaren'],
        'm' => ['maand', 'maanden'],
        'w' => ['week', 'weken'],
        'd' => ['dag', 'dagen'],
        'h' => ['uur', 'uren'],
        'i' => ['minuut', 'minuten'],
        's' => ['seconde', 'seconden']
    );

    $parts = array();
    foreach ($periods as $k => &$v) {
        if ($diff->$k) {
            $parts[] = $diff->$k . ' ' . $v[$diff->$k > 1];
        }
    }

    if (!$full) $parts = array_slice($parts, 0, 1);
    return $parts ? implode(', ', $parts) . ' ago' : 'just now';
}

Sample usage:

echo time_elapsed_string('2020-03-21 00:30:16') . PHP_EOL;
echo time_elapsed_string('2020-03-21 00:30:16', true) . PHP_EOL;

Output:

2 maanden ago
2 maanden, 1 week, 3 dagen, 14 uren, 6 minuten, 55 seconden ago

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95