I have below code which shows time
$now = date_create(date("Y-m-d H:i:s"));
$replydue = date_create($listing['replydue_time']);
$timetoreply = date_diff($replydue, $now);
echo $timetoreply->format('%H:%I')
Byt my problem is if difference is more than 24 hrs, it breaks time in more 24 hrs and shows 1 or 2 or any hours but below 24 hrs.
How can i show real hours difference like 74 hrs!
Thanks,
Ideally I'd prefer the following approach.. rather than reinvent the wheel or do lots of manual conversions:
$now = new DateTime();
$replydue = new DateTime($listing['replydue_time']);
$timetoreply_hours = $timetoreply->days * 24 + $timetoreply->h;
echo $timetoreply_hours.':'.$timetoreply->format('%I');
From the manual:
days: If the DateInterval object was created by DateTime::diff(), then this is the total number of days between the start and end dates. Otherwise, days will be FALSE.
Please note this assumes that all days are 24hrs which may not be the case in areas with DST
I have written the following function to assist with this:
/**
* @param DateTimeInterface $a
* @param DateTimeInterface $b
* @param bool $absolute Should the interval be forced to be positive?
* @param string $cap The greatest time unit to allow
*
* @return DateInterval The difference as a time only interval
*/
function time_diff(DateTimeInterface $a, DateTimeInterface $b, $absolute=false, $cap='H'){
// Get unix timestamps
$b_raw = intval($b->format("U"));
$a_raw = intval($a->format("U"));
// Initial Interval properties
$h = 0;
$m = 0;
$invert = 0;
// Is interval negative?
if(!$absolute && $b_raw<$a_raw){
$invert = 1;
}
// Working diff, reduced as larger time units are calculated
$working = abs($b_raw-$a_raw);
// If capped at hours, calc and remove hours, cap at minutes
if($cap == 'H') {
$h = intval($working/3600);
$working -= $h * 3600;
$cap = 'M';
}
// If capped at minutes, calc and remove minutes
if($cap == 'M') {
$m = intval($working/60);
$working -= $m * 60;
}
// Seconds remain
$s = $working;
// Build interval and invert if necessary
$interval = new DateInterval('PT'.$h.'H'.$m.'M'.$s.'S');
$interval->invert=$invert;
return $interval;
}
This can be used:
$timetoreply = time_diff($replydue, $now);
echo $timetoreply->format('%r%H:%I');
N.B. I have used format('U')
instead of getTimestamp()
because of the comment in the manual.
Also not that 64-bit is required for post-epoch and pre-negative-epoch dates!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With