wolfgang1983 wolfgang1983 - 1 month ago 7
PHP Question

Change elapsed time after a month to different format

I am using codeigniter and I have this code below It converts date in to a elapsed time to something like

Asked 1 month, 3 weeks ago


If the date is older than a month I would like it to only display like date
Asked Sept 01 05:34:13
and if older than a year
Asked Sept 01 2015 05:34:13


Currently if time is under month prints out like below which is fine

example Asked 1 minute, 14 seconds ago

example Asked 2 weeks, 3 hours ago

$this->when_was_question_posted(strtotime('2016-09-01 05:34:13'))



Question how can I make sure that if the date is older than a month
then display like date
Asked Sept 01 05:34:13
and if older than a
year
Asked Sept 01 2015 05:34:13



function when_was_question_posted($distant_timestamp, $max_units = 2) {
$i = 0;
$time = time() - $distant_timestamp; // to get the time since that moment

$tokens = [
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
];

$responses = [];

while ($i < $max_units) {
foreach ($tokens as $unit => $text) {
if ($time < $unit) {
continue;
}
$i++;
$numberOfUnits = floor($time / $unit);

$responses[] = $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
$time -= ($unit * $numberOfUnits);
break;
}
}

if (!empty($responses)) {
return 'Asked ' . implode(', ', $responses) . ' ago';
}

return 'Just now';
}


enter image description here

Answer

Here is something to get you going...

$date_now = new DateTime();
$date     = new DateTime('2014-04-01 00:00:00');

$interval = $date_now->diff($date);

if($interval->y > 0) {
    echo "More than a year";
    echo "<br>";
    $display_date = $date->format('M d Y h:i:s');
} elseif($interval->m > 0) {
    echo "More than a month";
    echo "<br>";
    $display_date = $date->format('M d h:i:s');
} else {
    // Call your existing function
}
Comments