Formatting number of days values in Months ,Days

//This function is usedful for calculate the Date difference between two date
//difference in days.for example start date is 01/01/2010 and end date is
//01/15/2010. their date difference is 457 days and we want to show output of 45
//days like " 1 months 15 days"

//You call function like this in your code

DateTime StartDate = Convert.ToDateTime("01/1/2010");
DateTime EndDate = Convert.ToDateTime("02/15/2010");
string strResult = ConvertDaysToMonths(StartDate, EndDate);

public string ConvertDaysToMonths(DateTime StartDate, DateTime EndDate)
DateTime oldDate;

DateTime.TryParse(StartDate.ToShortDateString(), out oldDate);
DateTime currentDate = EndDate;

TimeSpan difference = currentDate.Subtract(oldDate);

// This is to convert the timespan to datetime object
DateTime DateTimeDifferene = DateTime.MinValue + difference;

// Min value is 01/01/0001
// subtract our addition or 1 on all components to get the actual date.
int InYears = DateTimeDifferene.Year - 1;
int InMonths = DateTimeDifferene.Month - 1;
int InDays = DateTimeDifferene.Day - 1;

return ((InYears * 12) + InMonths).ToString() + " Months " + InDays.ToString() + " Days";


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: