Thursday, May 24, 2012

Calculating the Years and Months Between Two Dates

I ran into an interesting problem that had a much shorter solution than I anticipated. I searched the web for simple solutions and ran across this post on msdn (http://forums.asp.net/t/1289294.aspx/1?TimeSpan+Years+and+Months). Suppose you have 2 dates and want to find the following information about the dates range:
  • Number of years
  • Number of months
  • Number of quarters
  • Number of half years
Often I will test algorithms in Powershell (or some scripting language) and then convert them in what whatever static language I need it to be in; this is one of those cases.
$d1 = [DateTime]::Parse("5/3/2022");
$d2 = [DateTime]::Parse("2/2/2012");
$d3 = [DateTime]::MinValue + ($d1 - $d2)
$d3.Year - 1 # 10
$d3.Month - 1 # 3
$d3.Day - 1 # 1
There are some assumptions that I am making in a couple calculations for my application. I only care about whole periods, so I will be using the floor function to select the correct count. I am also ignoring the days, they don't matter.
TimeSpan span = AmortSched.FirstPrincipalPymntDate - AmortSched.FirstPrincipaMatDate;
DateTime range = DateTime.MinValue + span;

int yearCount = range.Year - 1;
int monthCount = range.Month - 1;
int totalMonthCount = (yearCount * 12) + monthCount;
int totalQuarterCount = Math.Floor(totalMonthCount / 3);
int totalHalfYearsCount = Math.Floor(totalMonthCount / 6);

No comments: