Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show PHP time as hours greater than 24 hrs like 70 hrs

Tags:

php

time

mysql

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,

like image 942
rjcode Avatar asked May 06 '15 10:05

rjcode


1 Answers

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!

like image 113
Arth Avatar answered Sep 27 '22 17:09

Arth