15

I have two date's

$date1 = "2014-02-11 04:04:26 AM" $date2 = "2014-02-11 05:36:56 AM" 

I want to calculate the difference and display it as follows

1 hour 32 minutes

0

2 Answers 2

40

Make use of DateTime::diff of the DateTime Class

<?php $datetime1 = new DateTime('2014-02-11 04:04:26 AM'); $datetime2 = new DateTime('2014-02-11 05:36:56 AM'); $interval = $datetime1->diff($datetime2); echo $interval->format('%h')." Hours ".$interval->format('%i')." Minutes"; 

OUTPUT :

1 Hours 32 Minutes 
Sign up to request clarification or add additional context in comments.

5 Comments

One simple question,How can I convert 1 hours 32 minutes to hour.I mean I want to the result in hour.Any Idea?
I don't get your question. What do you want as an expected output ?
You mean like 1 Hours 30 Minutes -> 1.5 Hours? Just divide the minute with 60.
I presume that if $datetime2 = new DateTime('2014-03-11 05:36:56 AM'); the answer will be the same...
If the difference between the dates is more than 24 hours, then the result is wrong. This answer will give hours only between 0 and 23.
15

Simply convert both dates to timestamp if dont want to do it in complex way... Something like this

$dateDiff = intval((strtotime($date1)-strtotime($date2))/60); $hours = intval($dateDiff/60); $minutes = $dateDiff%60; 

and there you go...

Thank you...

3 Comments

Your answer is correct but you have to subtract date1 from date1.
How to find $seconds also?
to get days you have to do this '$days = intval($duree/(60*24)); $hours = intval($duree/60)%24; $minutes = $duree%60; return "$days J $hours H $minutes m";'

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.