Click here to Skip to main content
16,018,818 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
I have to calculate the total number of years (i.e) my date of joining is on 08-01-2009
i have to calculate the number of years till date and display it in the dropdown as follows
2009
2010
2011
2012
Posted

Use and extension method:

    public static class ExtensionMethods
    {
        public static IEnumerable<int> GetYearsUntilNow(this DateTime startDate)
        {
            for (int year = startDate.Year; year <= DateTime.Now.Year; ++year)
            {
                yield return year;
            }
        }
    }
</int>


Then call it:

C#
var startDate = new DateTime(2009, 1, 8);
var years = startDate.GetYearsUntilNow();
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 7-Feb-12 21:50pm    
Not just solved this trivial problem, but in an elegant way, appreciated by my 5 :-)
--SA
SteveAdey 8-Feb-12 10:13am    
Thanks for the 5 Sergey
a rough solution for your problem:

int Total_year=System.DateTime.Year.Now-year_of_joining
 
Share this answer
 
Comments
Christian Graus 7-Feb-12 12:27pm    
This is very rough and no where near as good as the one already provided. In fact, your solution does not even compile or work.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900