user3838132
user3838132

Reputation: 31

How can I calculate the number of days between 2 variable dates in PHP?

I searched online but couldn't see much help on this.

Is there a ready to use function to do this in PHP that I haven't found?

I want to calculate the number of days between 2 variable dates e.g.:

$date1 = '01/08/2014'; $date2 = '07/08/2014;

I tried the below but $count is null:

<?php

$date1 = '01/01/14';
$date2 = '07/01/14';

$count = $date1->diff($date2);

echo $count;

?>

Upvotes: 0

Views: 126

Answers (4)

MH2K9
MH2K9

Reputation: 12039

 $now = time(); // or your date as well
 $your_date = strtotime("2010-01-01");
 $datediff = $now - $your_date;
 echo floor($datediff/(60*60*24));

Upvotes: 3

Rex Rex
Rex Rex

Reputation: 1030

Use DateTime::diff (aka date_diff):

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
Or:

$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);

You can then get the interval as a integer by calling $interval->days.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Better:

$from = DateTime::createFromFormat("d/m/Y",$date1);
$to = DateTime::createFromFormat("d/m/Y",$date2);
$diff = $from->diff($to,true);
$days = $diff->days;

Upvotes: 5

swiss_blade
swiss_blade

Reputation: 541

Or you can even use PHP's date_diff function like this:

$interval = $date1->diff($date2);

http://php.net/manual/en/datetime.diff.php

Upvotes: 0

Related Questions