Dear friends in most of the cases you need to work on dates. I had been stuck while calculating exact age of a person or total experience in Years, Months and Days. So, I googled to find the code that can help me to work on. But, I found that most of the programmers made mistakes in calculating exact difference in days or the code found to be too much complex to understand.
Actually calculating the date difference is so easy. Its similar to find the difference between two numbers, yet its quite tricky to calculate no of days exactly. I haven't added any validation check to avoid getting negative no of years if 'from date' is greater than 'to date'.
I created class library with name "AgeCalculator" and another console application "AgeCalculator.Tests" to test the classes in class library.
You can get the complete project here.
AgeCalculator consist of two class files Age.cs and Calculator.cs. Code snippets of these files are listed as follows.
File Name : Age.cs
namespace AgeCalculator
{
/// <summary>
///
/// </summary>
public class Age
{
public int Days { get; set; }
public int Months { get; set; }
public int Years { get; set; }
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format("{0} Year(s) {1} Month(s) {2} Day(s)", this.Years, this.Months, this.Days);
}
}
}
File Name : Calculator.cs
using System;
namespace AgeCalculator
{
/// <summary>
/// Calculates the age from specified dates.
/// </summary>
public class Calculator
{
/// <summary>
/// Calculates the age from specified from date and to date.
/// </summary>
/// <param name="fromDate">From date.</param>
/// <param name="toDate">To date.</param>
/// <param name="includeEndDay">if set to <c>true</c> [include end day].</param>
/// <returns></returns>
public static Age Calculate(DateTime fromDate, DateTime toDate, bool includeEndDay)
{
var days = toDate.Day - fromDate.Day + (includeEndDay ? 1 : 0);
var months = toDate.Month - fromDate.Month;
var years = toDate.Year - fromDate.Year;
// If days are -ve then borrow no of days from last month.
if (days < 0)
{
// If its January then borrow no of days from last year December.
if (toDate.Month == 1)
{
days = days + DateTime.DaysInMonth(toDate.Year - 1, 12);
}
else // If its not January then borrow days from last month of current year.
{
days = days + DateTime.DaysInMonth(toDate.Year, toDate.Month);
}
months = months - 1;
}
// If months are -ve then borrow 12 months from years.
if (months < 0)
{
months = months + 12;
years = years - 1;
}
return new Age { Days = days, Months = months, Years = years };
}
/// <summary>
/// Calculates the age from specified date.
/// </summary>
/// <param name="fromDate">From date.</param>
/// <param name="includeEndDay">if set to <c>true</c> [include end day].</param>
/// <returns></returns>
public static Age Calculate(DateTime fromDate, bool includeEndDay)
{
return Calculator.Calculate(fromDate, DateTime.Today, includeEndDay);
}
}
}
The code snippet of Calculate function is self explanatory. Firstly it is calculating the difference directly between years, months and days. After that if days are negative then it will borrow no of days from last month of toDate. If no of months is negative then it will borrow 12 months from last year of toDate.
Following are code snippets to calculate the date difference.
File Name : Program.cs
using System;
namespace AgeCalculator.Tests
{
internal class Program
{
private static void Main(string[] args)
{
DateTime birthDate = new DateTime(1986, 8, 12);
Console.WriteLine("Age of a Person till {0:dd-MMM-yyyy} : {1}.", DateTime.Today, Calculator.Calculate(birthDate, false));
// Experience between dates 06-Jan-2011 to 01-Feb-2016.
Console.WriteLine("Total Experience : {0}.", Calculator.Calculate(new DateTime(2011, 1, 6), new DateTime(2017, 2, 1), false));
}
}
}
Here, system date is : 23-Feb-2017, so after executing above code you will get following result.
I hope this will help. You can use the code as is or change the code logic as per your requirement. Please suggest improvements if any. Enjoy the coding...
Actually calculating the date difference is so easy. Its similar to find the difference between two numbers, yet its quite tricky to calculate no of days exactly. I haven't added any validation check to avoid getting negative no of years if 'from date' is greater than 'to date'.
I created class library with name "AgeCalculator" and another console application "AgeCalculator.Tests" to test the classes in class library.
You can get the complete project here.
AgeCalculator consist of two class files Age.cs and Calculator.cs. Code snippets of these files are listed as follows.
File Name : Age.cs
namespace AgeCalculator
{
/// <summary>
///
/// </summary>
public class Age
{
public int Days { get; set; }
public int Months { get; set; }
public int Years { get; set; }
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String" /> that represents this instance.
/// </returns>
public override string ToString()
{
return string.Format("{0} Year(s) {1} Month(s) {2} Day(s)", this.Years, this.Months, this.Days);
}
}
}
File Name : Calculator.cs
using System;
namespace AgeCalculator
{
/// <summary>
/// Calculates the age from specified dates.
/// </summary>
public class Calculator
{
/// <summary>
/// Calculates the age from specified from date and to date.
/// </summary>
/// <param name="fromDate">From date.</param>
/// <param name="toDate">To date.</param>
/// <param name="includeEndDay">if set to <c>true</c> [include end day].</param>
/// <returns></returns>
public static Age Calculate(DateTime fromDate, DateTime toDate, bool includeEndDay)
{
var days = toDate.Day - fromDate.Day + (includeEndDay ? 1 : 0);
var months = toDate.Month - fromDate.Month;
var years = toDate.Year - fromDate.Year;
// If days are -ve then borrow no of days from last month.
if (days < 0)
{
// If its January then borrow no of days from last year December.
if (toDate.Month == 1)
{
days = days + DateTime.DaysInMonth(toDate.Year - 1, 12);
}
else // If its not January then borrow days from last month of current year.
{
days = days + DateTime.DaysInMonth(toDate.Year, toDate.Month);
}
months = months - 1;
}
// If months are -ve then borrow 12 months from years.
if (months < 0)
{
months = months + 12;
years = years - 1;
}
return new Age { Days = days, Months = months, Years = years };
}
/// <summary>
/// Calculates the age from specified date.
/// </summary>
/// <param name="fromDate">From date.</param>
/// <param name="includeEndDay">if set to <c>true</c> [include end day].</param>
/// <returns></returns>
public static Age Calculate(DateTime fromDate, bool includeEndDay)
{
return Calculator.Calculate(fromDate, DateTime.Today, includeEndDay);
}
}
}
The code snippet of Calculate function is self explanatory. Firstly it is calculating the difference directly between years, months and days. After that if days are negative then it will borrow no of days from last month of toDate. If no of months is negative then it will borrow 12 months from last year of toDate.
Following are code snippets to calculate the date difference.
File Name : Program.cs
using System;
namespace AgeCalculator.Tests
{
internal class Program
{
private static void Main(string[] args)
{
DateTime birthDate = new DateTime(1986, 8, 12);
Console.WriteLine("Age of a Person till {0:dd-MMM-yyyy} : {1}.", DateTime.Today, Calculator.Calculate(birthDate, false));
// Experience between dates 06-Jan-2011 to 01-Feb-2016.
Console.WriteLine("Total Experience : {0}.", Calculator.Calculate(new DateTime(2011, 1, 6), new DateTime(2017, 2, 1), false));
}
}
}
Here, system date is : 23-Feb-2017, so after executing above code you will get following result.
I hope this will help. You can use the code as is or change the code logic as per your requirement. Please suggest improvements if any. Enjoy the coding...