You can consider those cases too.
Consider 2 dates 2nd Mar 2008
and 5th Jun 2013
.
Mar
2008 ________###########################
2009 ###################################
2010 ###################################
2011 ###################################
2012 #################################### (leap)
2013 ###############--------------------
Jun
You can subtract the years in between (ie 2009, 2010, 2011, 2012). Now here 2012 is a leap year but it doesn't matter because it will be counted in years not months.
Years = 4
Now, you are left with this
2
Mar 08 ____################################
Apr 08 ####################################
May 08 #####################################
Jun 08 ####################################
Jul 08 #####################################
Aug 08 #####################################
Sep 08 ####################################
Oct 08 #####################################
Nov 08 ####################################
Dec 08 #####################################
Jan 12 #####################################
Feb 12 ###################################
Mar 12 #####################################
Apr 12 ####################################
May 12 #####################################
Jun 12 #########----------------------------
5
Just count the full months. It doesn't matter how many days they contains. They are being counted in months not days.
Months = 14
2
Mar 08 ____################################
Jun 12 #########----------------------------
5
Now count the remaining days in Mar2008 and Jun2012 (excluding the end dates). Here the count comes out to be 29(Mar) + 4(Jun) = 33.
Days = 33
But 33 days seems odd as it can be converted into 1month + some days. If this happens, the question arises which month to choose - either Mar(31 days), Jun(30 days) or just reduce 30days to add a month. I think while considering huge differences, this would hardly matter. If we consider March, then the difference would be
4 Years 15 Months 2 Days
or simply 5 Years 3 Months 2 Days
The same approach can be continued for time.
EDITED
Let `date1` be greater than `date2`
Let max(month) gives the total days in the month
years = date1.year - date2.year - 1;
months = date1.month - date2.month - 1;
days = (max(date2.month) - date1.day) + (date2.day - 1);
if(days >= 30) //Here you can take totals days in date1 or date2
{
month++;
days-=30;
}
while(month >= 12) //Here month can reach a value of 24 because it can be incremented above too
{
years++;
month-=12;
}
print("Difference is " + years + " years " + month + " months " + days + " days");