Formatting number of days values in Years, Months ,Days


This function is useful for calculate the Date difference between two date difference in days

This function is useful for calculate the Date difference between two date
difference in days.for example start date is 01/1/2010 and end date is 04/3/2011. their date difference is 457 days and we want to show output of 457 days like "1 year 3 months 2 days"

You call function like this in your code


DateTime StartDate = Convert.ToDateTime("01/1/2010");
DateTime EndDate = Convert.ToDateTime("04/3/2011");
string strResult = CalculateDays(StartDate, EndDate);

public string CalculateDays(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.ToString() +" Years "+ InMonths.ToString() +" Months " + InDays.ToString() +" Days";
}


Comments

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:
    Email: