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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend4days leftRegister
Posted Jan 25, 2013, 1:38 AM EST
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.
VulpesRank #55 · 29.2K reputationPosted Jan 25, 2013, 2:07 AM EST
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.