-2

Need help to find a function in PHP which would return me the number of years ,months and dates between 2 given dates

For Eg: DATEDIF("20-05-2015","20-05-2015","m") would return 1 month in excel but while using the date_diff i would just get 31 days .

alanvabraham
  • 779
  • 2
  • 14
  • 25
  • possible duplicate of [How to calculate the difference between two dates using PHP?](http://stackoverflow.com/questions/676824/how-to-calculate-the-difference-between-two-dates-using-php) – Don't Panic May 11 '15 at 18:11

1 Answers1

0

The correct way to work with dates in PHP >= 5.2.0 is using DateTime, i.e.:

$startRaw = '2013-05-10 12:04:58';
$start = DateTime::createFromFormat('Y-m-d H:i:s', $startRaw );

$endRaw = date("2015-05-10 12:04:58");
$end = DateTime::createFromFormat('Y-m-d H:i:s', $endRaw );

$diff = $start->diff($end);
echo 'Difference: ' . $diff->format('%y years') . "\n";

Output:

Difference: 2 years

Demo:

http://ideone.com/3GzQsU


format

The following characters are recognized in the format parameter string. Each format character must be prefixed by a percent sign (%).

% Literal % % 
Y Years, numeric, at least 2 digits with leading 0 01, 03 
y Years, numeric 1, 3 
M Months, numeric, at least 2 digits with leading 0 01, 03, 12 
m Months, numeric 1, 3, 12 
D Days, numeric, at least 2 digits with leading 0 01, 03, 31 
d Days, numeric 1, 3, 31 
a Total amount of days 4, 18, 8123 
H Hours, numeric, at least 2 digits with leading 0 01, 03, 23 
h Hours, numeric 1, 3, 23 
I Minutes, numeric, at least 2 digits with leading 0 01, 03, 59 
i Minutes, numeric 1, 3, 59 
S Seconds, numeric, at least 2 digits with leading 0 01, 03, 57 
s Seconds, numeric 1, 3, 57 
R Sign "-" when negative, "+" when positive -, + 
r Sign "-" when negative, empty when positive -,  

Learn more about The DateTime class

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268