CodeIgniter Forums
Time calculation between 2 dates - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forum-5.html)
+--- Forum: Libraries & Helpers (https://forum.codeigniter.com/forum-11.html)
+--- Thread: Time calculation between 2 dates (/thread-67711.html)



Time calculation between 2 dates - sakthisiga - 03-30-2017

Hi Friends,

I have 2 dates with time as below:

From: 2017-03-09 09:26:00
To: 2017-03-11 09:25:00

I need to calculate exact Hour and minutes difference between 2 dates.. However I could get only 23:00 for diff functions.

I need the exact hours and minutes difference..

Please help


RE: Time calculation between 2 dates - suhindra - 03-30-2017

PHP Code:
$from strtotime("2017-03-09 09:26:00");
$to strtotime("2017-03-11 09:25:00");
echo 
round(abs($to $from) / 60,2). " minute"



RE: Time calculation between 2 dates - dave friend - 03-30-2017

Perhaps not the most elegant - but it works.
PHP Code:
 
  $start 
= new DateTime("2017-03-09 09:26:00");
 
 $end = new DateTime("2017-03-11 09:25:00");
 
 $interval $start->diff($end);
 
 $hrs $interval->24 $interval->h;
 
 echo $hrs." hours ".$interval->format('%i')." minutes"



RE: Time calculation between 2 dates - salain - 03-31-2017

@dave friend solution can be slightly simplify


PHP Code:
 $start = new DateTime("2017-03-09 09:26:00");
 
 $end = new DateTime("2017-03-11 09:25:00");
 
 $interval $start->diff($end);
 
 echo $interval->format('%h hours %i minutes %S seconds'); 



RE: Time calculation between 2 dates - dave friend - 03-31-2017

(03-31-2017, 12:14 AM)salain Wrote: @dave friend solution can be slightly simplify


PHP Code:
 $start = new DateTime("2017-03-09 09:26:00");
 
 $end = new DateTime("2017-03-11 09:25:00");
 
 $interval $start->diff($end);
 
 echo $interval->format('%h hours %i minutes %S seconds'); 

@salain, But that won't give the right answer if the interval is more than a day. Those hours must me added to the result.


RE: Time calculation between 2 dates - salain - 03-31-2017

@dave friend you are right, but your option would also be wrong if it is more than a month.


RE: Time calculation between 2 dates - marksman - 03-31-2017

strtotime is the best option for me Smile


RE: Time calculation between 2 dates - dave friend - 03-31-2017

(03-31-2017, 06:10 AM)salain Wrote: @dave friend you are right, but your option would also be wrong if it is more than a month.

An excellent point!

This revised code handles that.

PHP Code:
$start = new DateTime("2017-03-09 09:26:00");
$end = new DateTime("2017-04-09 09:26:00");
$interval $start->diff($end);
$hrs $interval->days 24 $interval->h;
echo 
$hrs." hours ".$interval->format('%i')." minutes"



RE: Time calculation between 2 dates - Narf - 03-31-2017

(03-31-2017, 06:17 AM)marksman Wrote: strtotime is the best option for me Smile

strtotime() is the worst thing ever.