Put out the age of a date in words

Recently, I have to output the age of a date in words and didn’t have a framework to work with. The first steps were to parse the given date into an array and create a timestamp with the individual parts. The difference between the timestamp of now and the created timestamp yielded the age in seconds. The result can be used to compare with seconds of a day, week, etc.

The following snippet outputs the age of a date in day, if the given date is less than seven days, in weeks if it’s less than four weeks an so on.

$date_parsed = date_parse($date);<br />$date_timestamp = mktime(0,0,0, $date_parsed['month'], $date_parsed['day'], $date_parsed['year']);<br /><br />$now_timestamp = time();<br />$timestamp_diff = $now_timestamp - $date_timestamp;<br /><br />if ($timestamp_diff < (60*60*24*7)) {<br />	return floor($timestamp_diff/60/60/24)." Days";<br />} elseif ($timestamp_diff < (60*60*24*7*4)) {<br />	return floor($timestamp_diff/60/60/24/7)." Weeks";<br />} else {<br />	return floor($timestamp_diff/60/60/24/30)." Months";<br />}
Veröffentlicht am
Kategorisiert in PHP

4 Kommentare

  1. Just past week I had to implement the same, here is the result:

    function ago( /*timestamp*/ $date ) {
    $ago = time() – $date;

    $ranges = array(
    31536000 => array( ‚year‘, ‚years‘ ),
    2419200 => array( ‚month‘, ‚months‘ ),
    604800 => array( ‚week‘, ‚weeks‘ ),
    86400 => array( ‚day‘, ‚days‘ ),
    3600 => array( ‚hour‘, ‚hours‘ ),
    60 => array( ‚minute‘, ‚minutes‘ ),
    );

    $parts = array();
    foreach( $ranges as $seconds => $sufix ) {
    $t = floor($ago / $seconds);

    if ( $t > 0 ) {
    return $t . ‚ ‚ . $sufix[ $t>1 ? 1 : 0 ] . ‚ ago‘;
    }
    }

    return ‚just now‘;
    }

  2. You can modify it to include years as well. Here’s my modified version which changes your last „else {“ loop

    } else {
    $total_months = $months = floor($timestamp_diff/60/60/24/30);
    if($months >= 12) {
    $months = ($total_months % 12);
    $years = ($total_months – $months)/12;
    echo $years . “ Years „;
    }
    if($months > 0)
    echo $months . “ Months“;
    }

    PS; I’ve changed the „return“ to „echo“ – just for testing purposes

  3. I came across a handy piece of code to print out the “age of a date” in words on ThinkPHP. This code should print out the difference between two dates in words (X Days/Months/Weeks/Years). I have modified the original piece of code to prin…

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert