how to get year difference from today's date in c#
suppose i have datepicker is 11/12/2011.so compare this date with today's date.
year difference want in float
mean 1.5
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
VulpesPosted Jan 25, 2013, 7:07 AM
DateTime d1 = Convert.ToDateTime("11/12/2011").Date;
DateTime d2 = DateTime.Today;
float years = (d2.Year - d1.Year) + (d2.Month - d1.Month)/12f + (d2.Day - d1.Day)/365.25f;
MessageBox.Show(years.ToString());
Relative to today (25 Jan 2013), this gives results of
1.083333 for 25 Dec 2011
1.166667 for 25 Nov 2011
1.121663 for 11 Dec 2011
As it's not clear what to do about days when either year is a leap year, an 'average' divisor of 365.25 is used.
Posted Jan 25, 2013, 6:38 AM
DateTime oldDate = Convert.ToDateTime("11/12/2011").Date;
DateTime currentDate = System.DateTime.Today.Date;
TimeSpan difference = currentDate - oldDate ;
int days = difference.Days;
float years =days/365;
double remainder = (days % 365);
float fraction = Convert.ToSingle( remainder /182.5);
years = years + fraction;
MessageBox.Show(years.ToString());
Hope this will help you.