Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate months, years and days between two given dates as timestamp [duplicate]

Tags:

php

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

like image 930
Satish Sharma Avatar asked Nov 27 '22 22:11

Satish Sharma


2 Answers

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');
like image 134
Louis Huppenbauer Avatar answered Dec 06 '22 00:12

Louis Huppenbauer


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

like image 43
user1909426 Avatar answered Dec 05 '22 23:12

user1909426