Find number of years, months and days between two dates using C#

Subscribe to the Technacular RSS feed  RSS Feed or by Email and receive free daily updates

Recently I ran into a situation where I had the start date and the end date and had to store the start date and the difference between the end and the start date (in terms of years, months, days) as string.

Here is a C# code to do that:

public static string DateDiff(DateTime startDate, DateTime endDate)
{
   string timeStr = string.Empty;
   int yr = 0;
   int mth = 0;
   int days = 0;

   TimeSpan ts = new TimeSpan();
   ts = endDate.Subtract(startDate);
   yr = (ts.Days/365);

   do
   {
       for(int i=0; i <= 12; i++)
       {
         if(endDate.Subtract(startDate.AddYears(yr).AddMonths(i)).Days > 0)
         {
             mth = i;
          }
          else
          {
             break;
          }
        }

        if(mth > 12)
           yr = yr + 1;
    }while(mth > 12);

    days = endDate.Subtract(startDate.AddYears(yr).AddMonths(mth)).Days;

    if(yr > 0)
                timeStr += yr.ToString() + “y”;
    if(mth > 0)
                timeStr += mth.ToString() + “m”;
    if(days > 0)
                timeStr += days.ToString() + “d”;

     return(timeStr);
}
How would you have done this?
Technorati tags: , , , , ,

Popularity: 5% [?]

Bookmark and Share: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • DZone
  • Furl
  • Reddit
  • Spurl
  • Technorati
  • IndianPad
  • StumbleUpon

Related Posts

  • Moving To Bangalore: Choosing an International Moving Company
  • Complete Coverage: Moving From USA To Bangalore
  • Find the running status of trains in India
  • Monitor Blogosphere For Search Terms Using RSS Feeds
  • Write a comment:

    Technology Blogs - Blog Top Sites Blog Flux Directory Blogarama - The Blog Directory BuzzBums Technology blogs Technology blogs blog search directory
    Dreamsubmitting Directory Free Link Directory