By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
429,616 Members | 2,026 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,616 IT Pros & Developers. It's quick & easy.

finding length of time from two date/time entries

100+
P: 110
I have a bunch of events which I extract from my database, some of these events extend over a night, some take place during a single day.

In the database I have the start/end times of the event, and I am trying to calculate the length of the event.

I've tried a ton of stuff, but I can't seem to get this working properly. If an event lasts from 10pm, Dec 2nd to 5am Dec3, I want it to return 7 hours.

Here's the code as I have it now.
Expand|Select|Wrap|Line Numbers
  1.  list($year2, $month2, $day2) = split('[/.-]', $row3['startDate']);
  2.  list($hour2, $min2, $sec2) = split(':', $row3['startTime']);
  3. $startAll = date('H:i:s, d-m-Y', mktime($hour2,$min2,$sec2, $month2, $day2, $year2));
  4.  
  5.  list($year3, $month3, $day3) = split('[/.-]', $row3['endDate']);
  6.  list($hour3, $min3, $sec3) = split(':', $row3['endTime']);
  7. $endAll = date('H:i:s, d-m-Y', mktime($hour3,$min3,$sec3, $month3, $day3, $year3));
  8.  
  9. $length = date('H:i', $endAll-$startAll);
  10.  
  11. echo $length.'<br />'.$startAll.'<br/>'.$endAll;
  12.  
This should be simple, but maybe it isn't
Thanks
Pete
Dec 16 '07 #1
Share this Question
Share on Google+
1 Reply


100+
P: 110
I'm answering my own thread here in the hope of helping somebody in the future.

previously I was trying to subtract an entire date/time range and it wasn't working for me.
Instead, I have converted the date/time to seconds and then subtract one from the other, then convert the result to hours. Pretty simple actually.

Expand|Select|Wrap|Line Numbers
  1.  list($year2, $month2, $day2) = split('[/.-]', $row3['startDate']);
  2.  list($hour2, $min2, $sec2) = split(':', $row3['startTime']);
  3. $startAll = date('U', mktime($hour2,$min2,$sec2, $month2, $day2, $year2));
  4.  
  5.  list($year3, $month3, $day3) = split('[/.-]', $row3['endDate']);
  6.  list($hour3, $min3, $sec3) = split(':', $row3['endTime']);
  7. $endAll = date('U', mktime($hour3,$min3,$sec3, $month3, $day3, $year3));
  8.  
  9. $length =  ($endAll-$startAll)/(60*60);
  10.  
I hope somebody finds this useful.
Dec 16 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.