-1

I have 2 outputs from following code:

$start_time = $dt->format('Y-m-d H:i:s');

$end_time = $dt->format('Y-m-d H:i:s');
  1. start_time - 2018-09-27 17:42:01
  2. end_time - 2018-09-27 17:42:16

How can i get the difference in minutes, even if the time diff is below 1 minute, like example 0.5 minutes (30 seconds).

I require only minutes value, even if it is part of a minute. How is it possible in php using time functions?

Thanks in advance.

Pamela
  • 684
  • 1
  • 7
  • 21

1 Answers1

1

$differenceInMinutes = (strtotime($end_time) - strtotime($start_time))/60

This converts your 2 dates into a unix time first by using strtotime() (PHP documentation). The unix time is always in seconds. Then when we subtract them from each other we get the difference in seconds between the two dates. To get from seconds to minutes you can of course divide by 60.

dWinder
  • 11,597
  • 3
  • 24
  • 39
Dirk Scholten
  • 1,013
  • 10
  • 19
  • Btw, he's creating the dates, so he could just use time() to retrieve the seconds. $start – Alberto Sep 27 '18 at 12:31
  • @Dirk Scholten The duration is displayed as 25634192 while storing in my mysql DB (Iint). Used only 19 seconds. – Pamela Sep 27 '18 at 12:33
  • That seems like a really odd date/time format. How do you get from that number to your actual dates? – Dirk Scholten Sep 27 '18 at 12:36
  • `strtotime` is not recommended, as Unix time can be limited to 32 bits, and those PHP builds (and OSes) are still out there. Use `DateTime` if you can, as this will do the calculation correctly regardless of the underlying architecture. Of course, it depends on your use-case - I think the year has to be >2037 in order for wrap-around to happen. – halfer Sep 27 '18 at 12:38
  • @Pamela Since they are both already DateTime objects you can then also use something like: `$dtEnd->diff($dtStart)->s/60` This does basically the same thing but with less steps in between. And like halfer said, this solution is a bit more future proof. – Dirk Scholten Sep 27 '18 at 12:51