3

I have two times like 10:00 am and 7:00 pm.

And from this I want to get the total hours. As from that time I have to get the 9 hours.

How will I do this?

I have explode it with the : but it then subtract 7 from 10 and return the result 3 which is incorrect because it should return 9.

Ahmad
  • 2,099
  • 10
  • 42
  • 79

5 Answers5

4
<?php echo  strtotime('7:00 pm')-strtotime('10:00 am');?>

Get the timestamp difference

EDIT

echo (strtotime('07:00 pm')-strtotime('10:00 am'))/(60*60); //displays 9

60*60 = 1 Hrs

EDIT

$fromTime = '3:00 pm';
$toTime = '12:00 am';
$timediff   =   (strtotime($toTime)-strtotime($fromTime))/(60*60);
echo $timediff >= 0 ?  $timediff : (24 + $timediff);
Duke
  • 35,420
  • 13
  • 53
  • 70
  • But it returns it in timestamp. I want the number 9. – Ahmad Mar 16 '12 at 06:27
  • but with 3:00 pm - 12:00 am it returns 15. which is incorrect. – Ahmad Mar 16 '12 at 06:47
  • @Ahmad Its Correct..[1 2 3 4 5 6 7 8 9 10 11] AM [12 1 2 3] PM = Total 15 Hrs – Duke Mar 16 '12 at 07:05
  • Its not correct. I am calculating the total hours spent in office. SO if office timing is from 3pm to 12am the total duty hours are 9. And it returns 15 which is incorrect. – Ahmad Mar 16 '12 at 07:16
1

You can use the strtotime function of PHP to convert this to unix time and so you can do the further calculation with it.

Dipu Raj
  • 1,784
  • 4
  • 29
  • 37
1

I assume you can get hold of the am or pm information! With this information you can make an if() to make it correct!

If() it is PM, add 12 hours, if it is not PM, don't do anything.

Do this with the times you're comparing:

if (pm==1){
time+=12;
}

so 10:00 am = false it will be 10:00 and 7:00 pm = true it will be 19:00

19:00 - 10:00 = 9 hours = win.

Community
  • 1
  • 1
Harry Svensson
  • 330
  • 4
  • 18
1

I feel this will help you out more effectively

<?php echo  date('H:i:s',strtotime('7:00 pm')-strtotime('10:00 am'));?>
Narayan Singh
  • 1,234
  • 2
  • 13
  • 26
0

Use DateTime interface, Its simple

    $day1= new DateTime("today 01:33:26am");
    $dayd2= new DateTime("today 10:40:36pm");         //Output: Hours: 21
    $interval= $day1->diff($day2);
    $h =  ($interval->days * 24) + $interval->h;
    echo "Hours: ".$h

Here h = number of hours. $interval->days means how many days get from difference if we get one(1) day then it's add 1*24(hours) = 24+21 = 46 hour's but here day1 and day2 contains today so, that's means 0*24 = 0 + 21 = 21

Finally Output: 21 hour's

Zakir
  • 1
  • 3