Hi guys.
I am using the following code to display how long ago something was (using the examples at the top of the code).
// Between a past time and now:
// $elapsed_time = elapsed(strtotime('2004-05-19'));
// $elapsed_time = elapsed(strtotime('2004-05-19 13:12:11'));
// Between two times:
// $elapsed_time = elapsed(strtotime('2004-05-19'), strtotime('2008-11-20'));
// Between a future time and now:
// $elapsed_time = elapsed(strtotime('2008-11-20'));
// Between a past time and now, with seconds included in the return 'string 'element:
// $elapsed_time = elapsed(strtotime('2004-05-19'), null, 'seconds');
// With days minumum (not hours, minutes, or seconds) in the 'string':
// $elapsed_time = elapsed(strtotime('2004-05-19'), null, 'days');
function elapsed($start_ts, $now_ts = null, $min_period = 'minutes')
{
$periods = array('years', 'months', 'days', 'hours', 'minutes', 'seconds');
if (empty($now_ts)) {
$now_ts = time();
}
$same = false;
if ($now_ts == $start_ts) {
$same = true;
} elseif ($now_ts < $start_ts) {
$tmp_ts = $now_ts;
$now_ts = $start_ts;
$start_ts = $tmp_ts;
}
$min_key = array_keys($periods, $min_period);
$ret['string'] = '';
foreach ($periods as $key => $period) {
$ret[$period] = 0;
if ($same) {
continue;
}
while (($start_ts = strtotime('+1 ' . $period, $start_ts)) < $now_ts) {
$ret[$period]++;
}
$start_ts = strtotime('-1 ' . $period, $start_ts);
if ($key > $min_key[0]) {
continue;
}
if ($ret[$period] !== 0) {
$ret['string'] .= $ret[$period] . ' ' . $period;
if ($ret[$period] === 1) {
$ret['string'] = substr($ret['string'], 0, strlen($ret['string']) - 1);
}
$ret['string'] .= ', ';
}
}
if (!$ret['string']) $ret['string'] = $ret['seconds'] . ' seconds';
$ret['string'] = rtrim($ret['string'], ', ');
return $ret;
}
The problem is that on the end of certain months, for example today (Mon 31st March) it always returns 0 seconds, nothing else.
Any idea why that is, and if it's fixable? Apart from that it works like a dream
I found out from someone trying to help that we can get calendar months via:
$daysInMonth = cal_days_in_month(CAL_GREGORIAN, $monthNumber, $yearNumber);
but I'm unsure how to integrate that with the PHP code?
Any help trying to resolve this woud be much appreciated. It's annoying!