0

Another date time problem.

I have a Time when something gets busy like -> "2021-02-24 12:00:00"(string)

I have the current date like this -> date('Y-m-d h:i:s') (string)

I need to calculate how many hours : minutes : seconds passed between the two. For example (gets busy at) 2021-02-14 15:00:00 current time is 2021-02-14 16:15:00 so I need to show something similar to this: 01:15:00.

But what if more than 99 hours passed, how do I make it so it looks like this -> 120:02:36.

The question I asked yesterday was not specified enough so I got some answers in here: (I know it's my bad)

PhP date time addition

but in the end I can't use it for this problem.

2 Answers2

2

If you convert the dates to timestamps, you can then use something like https://stackoverflow.com/a/3172368/1213708 to break the time down into hours/minutes/seconds.

The sprintf() is just a way of formatting the date with 2 digit minutes and seconds...

$inputDate = new DateTime("2021-02-22 12:00:00");
$nowDate = new DateTime();

$interval = abs($inputDate->getTimeStamp() - $nowDate->getTimeStamp());
$hours = floor($interval / 3600);
$minutes = floor(($interval / 60) % 60);
$seconds = $interval % 60;

echo sprintf("%d:%02d:%02d", $hours, $minutes, $seconds);

gave as output (recently)...

51:22:01
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
  • Why don't you use date_diff? The result via the time stamp does not provide the result that is expected if a time change (daylight saving time / winter time) lies within the interval. – jspit Feb 24 '21 at 17:58
  • @jspit as it gives a DateInterval which separates out the days/hours, it would be a case of multiplying the days and add them to the hours. It's an alternative though. – Nigel Ren Feb 24 '21 at 18:01
1

The DateTime extension dt has a special method for this problem: diffFormat().

echo dt::create('2021-02-22 12:00:00')->diffFormat("Now","%G:%I:%S");

Output few minutes ago:

55:52:36

jspit
  • 7,276
  • 1
  • 9
  • 17