1

Something is not working properly with the following code and I am going mad trying to understand why it is not calculating correctly:

$hours = date('H:i' , strtotime('03:00') - strtotime('02:00'));

echo $hours;

Result: 02:00

Expected Result: 01:00

Could anyone help me guessing what is going wrong?

02:00 as the result

2
  • But when try to run your code its shows 01:00 Commented Oct 7, 2016 at 11:28
  • 1
    @Albzi thank you for your answer. When I use only one strtotime, it calculated correctly. Commented Oct 7, 2016 at 11:48

2 Answers 2

3

You can use the DateTime object to accomplish it:

$date1 = new DateTime('03:00');
$date2 = new DateTime('02:00');
$dateInterval = $date1->diff($date2);

echo $dateInterval->format('%H:%S'); // result would be 01:00
Sign up to request clarification or add additional context in comments.

Comments

2

You probably want something like this instead:

$hours = date('H:i' , strtotime('03:00 - 02:00'));

Or even:

$hours = date('H:i' , strtotime('03:00 - 2 hours'));

This will print 01:00.

https://3v4l.org/on4JH

6 Comments

@LifeTimeProgrammer Look at this link: 3v4l.org/EIZ4s It shows OP's behavior he doesn't want.
yes i looked up. but when my local server its working as well as your code also .
That's PHP for you haha @LifeTimeProgrammer
Thanks for your answer!
@rjdown Nice catch. Time/date is a pain!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.