5

Possible Duplicate:
How to calculate the difference between two dates using PHP?
How to get difference between two dates in Year/Month/Week/Day?

i am trying to calculate years and months and days between two given dates in PHP.

i am also using timestamp of those date. is there any way to calculate years and months and

days from difference of those time stamp.

for example first date is 2 Jan, 2008. and second one is 5 July, 2012. and result is 4 Years 5 monts and 3 days.

i am working on timestamp as date input and want to know that is there any function available which directly calculate above things by two input timestamp

Community
  • 1
  • 1
Satish Sharma
  • 9,547
  • 6
  • 29
  • 51

4 Answers4

29

You could use the DateTime object for that (please note the missing "," in the datetime constructor).

$datetime1 = new DateTime('2 Jan 2008');
$datetime2 = new DateTime('5 July 2012');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%y years %m months and %d days');
Louis Huppenbauer
  • 3,719
  • 1
  • 18
  • 24
11

You can do this pretty easily with DateTime:

$date1 = new DateTime("2008-01-02");
$date2 = new DateTime("2012-07-05");
$diff = $date1->diff($date2);

echo "difference " . $diff->y . " years, " . $diff->m." months, ".$diff->d." days "

Documentation

user1909426
  • 1,658
  • 8
  • 20
2

You should have a look at Carbon, it's a pretty new PHP 5.3 lib on top of DateTime with a lot of usefull methods.

For Date diff:

<?php
$dtOttawa = Carbon::createFromDate(2000, 1, 1, 'America/Toronto');
$dtVancouver = Carbon::createFromDate(2013, 1, 1, 'America/Vancouver');
echo $dtOttawa->diffInHours($dtVancouver);
echo $dtOttawa->diffInDays($dtVancouver);
echo $dtOttawa->diffInMinutes($dtVancouver);
echo $dtOttawa->diffInYears($dtVancouver);

If you want Human readable diff:

$dt = Carbon::createFromDate(2011, 2, 1);

echo $dt->diffForHumans($dt->copy()->addMonth());              // 28 days before
echo $dt->diffForHumans($dt->copy()->subMonth());              // 1 month after
Damien
  • 5,872
  • 2
  • 29
  • 35
1

You can create two DateTime objects (www.php.net/datetime) from the timestamps. When calling the diff method you get a DateInterval object, which has properties for years and months.

Tobias
  • 1,692
  • 12
  • 21