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
Asked Sept 01 05:34:13
Asked Sept 01 2015 05:34:13
$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 dateand if older than aAsked Sept 01 05:34:13
yearAsked 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';
}
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
}