user1490612
user1490612

Reputation: 291

How to find time difference between 2 dates in php

I want to get the time difference between 2 dates in minutes. The 2 dates are in the following format

date1='05-11-2012 11:25:00'
date2='06-11-2012 17:45:00'

Upvotes: 0

Views: 789

Answers (4)

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

$datetime1 = new DateTime('05-11-2012 11:25:00');
$datetime2 = new DateTime('06-11-2012 17:45:00');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days'); //return +1 days
//or
$datetime1 = date_create('05-11-2012 11:25:00');
$datetime2 = date_create('06-11-2012 17:45:00');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days'); //return +1 days

for php <5.3

$date1 = '05-11-2012 11:25:00';
$date2 = '06-11-2012 17:45:00';
$diff = floor(abs( strtotime( $date1 ) - strtotime( $date2 ) )/(60*60*24));
printf("%d days\n", $diff); //return 1 days

Upvotes: 2

softsdev
softsdev

Reputation: 1509

$start_time = strtotime( "2012-10-12 11:35:00" );

$end_time = strtotime( "2012-10-13 12:42:50" );

echo round ( abs( $end_time - $start_time ) / 60,2 ). " minute";

This is different between two dates in MINUTES.

Upvotes: 0

Kevin Nielsen
Kevin Nielsen

Reputation: 4433

You neglected to indicate what format you'd like the time difference expressed in. If you're willing to work in seconds (which are easily converted), you could simply convert each date to a timestamp and then take the absolute difference using basic math. For instance, give $date1 = '05-11-2012 11:25:00' and $date2 = '06-11-2012 17:45:00':

$diff_seconds = abs( strtotime( $date1 ) - strtotime( $date2 ) );

And you could do whatever you like with the result.

Upvotes: 1

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

<?php
$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');
?>

For further reference please visit the following link http://php.net/manual/en/datetime.diff.php

Upvotes: 1

Related Questions