Click here to Skip to main content
15,867,308 members
Articles / Web Development / ASP.NET

Calculating Duration Between Two Dates in Years, Months and Days

Rate me:
Please Sign up or sign in to vote.
4.73/5 (47 votes)
25 Aug 2008CPOL5 min read 440.7K   15K   70   44
Calculate the accurate duration between two dates in years, months and days
DurationCalculatorApp

Introduction

I was looking for a Duration calculator between two dates which gives duration in number of years, number of months and number of days together. It can be defined as Age Calculator which is able to give any one’s exact age in years, months and days.

But unfortunately I didn't find exactly what I was looking for. Most of the calculators give output either in years or in months or in weeks or in days and so on and even in milliseconds, but not all the information together.

I realize that there should be something to calculate duration between two dates and give output in years, months and days together.

Problem

In most of the solutions for this problem, I found that the difference is calculated by the following procedure:

First calculate ‘TimeSpan’ from difference between two dates. Then from the time span, calculate days, from days calculate months, and from months or days calculate years.

This calculates right up to day calculation. But when you calculate month from day, then there is conflict. Because, the length of all the months (length means days) is not the same. Some months contain 28 days, some 30 and 31 for regular years. So, two months could be equivalent to 59 (January + February) days, 61 (March + April) days, 62 (July + August) days and even 60 (February leap year + March) days for leap year. After that when calculating years, there is another conflict, does the year contain 365 days or 366 days (in case of leap year)?

Actually this problem can be easily solved for a single year by adding many conditions. But for a long duration, it is difficult to trace all the leap years and finally generate accurate duration in days, months and years.

Background

Before starting the calculation, we just try to recollect our arithmetic operation basics. When we subtract 19 from 23 (23-19) then what happens? First we try to subtract the first digit ‘9’ (right side of 19) from first digit ‘3’ (right side of 23). Then we find that 3 is less than 9. So, add 10 with ‘3’ and subtract ‘9’ from (3+10); after that we add ‘1’ with ‘1’ second digit of 19 and subtract from the second digit ‘2’ of 23. We add 10 because the base of all the digits is 10.

In the same way, when we try to subtract one date from another (ignoring time) then we have to consider three different type/based numbers, that is day of the month; month of the year and year itself. Let's say we want to subtract date2 from date1 [date format YYY-mm-dd].

  • date1: 2000- 3- 1
  • date2: 1999- 4-10
  • dura: 0y - 10m - 21d

Here date1 is greater than date2, but day of the date1 ‘1’ is smaller then the day of the date2 ‘10’. So according to the arithmetic rule, before subtracting ‘10’ from ‘1’, we have to add a certain number (say x) with ‘1’ to the day of date1. Here x is equivalent to days (considering days is base of a month) of the month of date2. And also add ‘1’ with ‘4’ the month of date2. The number (x) will be different for different months, because different months contain different number of days. For example: for January x = 31, for February x= 28 or 29(for leap year) and so on.

After calculating days, we subtract the month of date2 ‘4’ including ‘1’ (according to day calculation) that is ‘4+1’ from ‘3’. As month of date1 (4+1=5) is less than the month of date2 ‘3’, we have to add 12 with month of date1 and add ‘1’ with year of date2. We are adding ‘12’ with month of date1 because each year contains exactly 12 months.

Finally, the year calculation is a simple arithmetic calculation.

Using the Code

Duration Calculation

Global Variables

C#
private int[] monthDay = new int[12] { 31, -1, 31, 30, 31, 30, 31, 31, 30, 31, 30,
31 };
private DateTime fromDate;
private DateTime toDate;
private int year;
private int month;
private int day; 
  • int[] monthDay’ defines Number of days in month, index 0=> January and 11=> December. February contain either 28 or 29 days, that's why here value is -1 which means it will be calculated later.
  • DateTime fromDate’ contain the start date value or smaller date value between two dates.
  • DateTime toDate’ contains the end date value or bigger date value between two dates.
  • int year’ contains year(s) of the output.
  • int month’ contains month(s) of the output.
  • int day’ contains day(s) of the output.

Prepare Data for Calculation

To calculate duration, we need two dates:

C#
public DateDifference(DateTime d1, DateTime d2)

Here d1 is the first date and d2 is the second date.

C#
if (d1 >d2)
{
    this.fromDate = d2;
    this.toDate = d1;
}
else
{
    this.fromDate = d1;
    this.toDate = d2;
} 

From the two dates, we identify which date is bigger. The bigger one is set as toDate and the smaller one is fromDate so that we always get a positive duration.

Calculation

Day Calculation
C#
increment = 0; 
if (this.fromDate.Day > this.toDate.Day)
{ 
    increment = this.monthDay[this.fromDate.Month - 1]; 
}

If ‘this.fromDate.Day’ is greater than ‘this.toDate.Day’, then we store the value in ‘increment’ which will be added to ‘this.toDate.Day’. To get the proper number ‘int[] monthDay’ will help us.

C#
if (increment== -1)
{
    if (DateTime.IsLeapYear(this.fromDate.Year))
    {
        increment = 29;
    } 
    else
    {
        increment = 28;
    }
}

Here we check if the month is February? If it is, then what are the number of days?

C#
if (increment != 0)
{    
    day = (this.toDate.Day+ increment) - this.fromDate.Day;
    increment = 1; 
}
else
{       
    day = this.toDate.Day - this.fromDate.Day;
}

The simple arithmetic operation is completed. And now ‘increment’ contains the number which will be added to ‘this.fromDate.Month’.

Up to this day, calculation is completed and ‘day’ contains the output’s day(s) result.

Month Calculation
C#
if ((this.fromDate.Month + increment) > this.toDate.Month)
{   
    this.month = (this.toDate.Month+ 12) - (this.fromDate.Month + increment);
       increment = 1;
}
else
{    
    this.month = (this.toDate.Month) - (this.fromDate.Month + increment);
    increment = 0;
}

Month calculation is very simple and almost like Day calculation. Here if ‘this.toDate.Month’ is smaller than the result of ( ‘this.fromDate.Month’ + ‘increment’), then just add ‘12’ to ‘this.toDate.Month’ and add ‘1’ to ‘this.fromDate.Year’ (which is stored in ‘increment’); Otherwise, it is just simple subtraction.

Here we add 12 because each year contains exactly 12 months.

Year Calculation
C#
this.year = this.toDate.Year - (this.fromDate.Year + increment);

This is just simple arithmetic operation. Nothing to say.

Final Results
C#
public int year;
public int month;
public int day;

These are the variables which contain the results of the calculation.

C#
public override string ToString()
{    
    return this.year + "Year(s), " + this.month + " month(s), " + this.day + " day(s)";
} 

To get the formatted output, we override the tostring method.

Output

Here is the output for the corresponding input. Input Date format is (yyyy-mm-dd) for user friendly view.

Input:
2000-12-1  
1999-2-3
Output: 1 Year(s), 9 month(s), 26 day(s)  

Input:
1984-2-14 
2008-8-20 
Output: 24 Year(s), 6 month(s), 6 day(s)  

Input: 
2008-7-14  
1960-6-14 
Output: 48 Year(s), 1 month(s), 0 day(s)  

Input: 
2008-7-14  
1960-6-14 
Output: 48 Year(s), 1 month(s), 0 day(s)  

Input: 
2008-7-13  
1960-5-5 
Output: 48 Year(s), 2 month(s), 8 day(s) 

Conclusion

This article will help you to find out the duration of dates in year, month and day format. The whole code is uploaded here, so anyone can play with it. And if there are any suggestions or corrections, please feel free to share.

History

  • 25th August, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer AIUB
Bangladesh Bangladesh
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionExcelent! Thnks Pin
Prof. Francisco Araújo19-Feb-21 7:22
Prof. Francisco Araújo19-Feb-21 7:22 
QuestionIn Java Please Pin
Urek24-Jul-18 0:57
Urek24-Jul-18 0:57 
QuestionVB.net Pin
Member 1340912114-Sep-17 16:11
Member 1340912114-Sep-17 16:11 
QuestionSame example in VBA Pin
Francisco Prado29-Apr-17 4:39
Francisco Prado29-Apr-17 4:39 
AnswerRe: Same example in VBA Pin
Ajos121-May-17 6:32
Ajos121-May-17 6:32 
AnswerI Need your Help ASAP Pin
Member 1340912114-Sep-17 16:54
Member 1340912114-Sep-17 16:54 
PraiseBest answer I can get on the internet! Pin
Member 1053215116-Mar-17 22:27
Member 1053215116-Mar-17 22:27 
QuestionIn VB please. Pin
Member 1240866424-Mar-16 9:42
Member 1240866424-Mar-16 9:42 
Questionnot accurate calculations Pin
Patil Kishor10-Dec-13 22:59
Patil Kishor10-Dec-13 22:59 
QuestionMore easy Pin
Gustavo Santis13-Mar-13 16:28
Gustavo Santis13-Mar-13 16:28 
AnswerRe: More easy Pin
Dinesh.V.Kumar29-Nov-13 1:17
Dinesh.V.Kumar29-Nov-13 1:17 
Questionty Pin
dipan chikani25-Aug-12 9:00
dipan chikani25-Aug-12 9:00 
GeneralYou are great!! Pin
AviMor24-May-12 11:08
AviMor24-May-12 11:08 
GeneralYou are great!! Pin
AviMor24-May-12 11:07
AviMor24-May-12 11:07 
GeneralMy vote of 5 Pin
Mardani Dani5-Jan-12 12:08
Mardani Dani5-Jan-12 12:08 
GeneralMy Vote of 5 Pin
RaviRanjanKr1-Dec-11 4:08
professionalRaviRanjanKr1-Dec-11 4:08 
GeneralMy vote of 5 Pin
ben jamir30-Nov-11 20:59
ben jamir30-Nov-11 20:59 
QuestionThanks [modified] Pin
mahesh__kumar__sharma9-Jul-11 1:58
mahesh__kumar__sharma9-Jul-11 1:58 
AnswerRe: Thanks Pin
acko0856-Sep-11 13:01
acko0856-Sep-11 13:01 
I think this is the simplest way to calculate difference between 2 dates (in y,m,d).
I used DateSerial function in VB.NET (I'm not sure if it exists in C#, but you can easily write one)

Here are the steps:
1. Rewind the startDate by startDate.Day-1 (we get 1 as the day for the startDate because Day is always >=1)
2. Rewind the stopDate by startDate.Day-1 (so the interval remains the same)
3. Subtract days from days,
months from months (if you get negative value add 12),
years from years (subtract 1 if you got negative value from months subtraction)

That's it!

VB
Public Function DateDiffYMD(ByVal startDate As Date, ByVal stopDate As Date) As Integer()
        Dim res() As Integer = {0, 0, 0}

        Dim offset As Integer = startDate.Day - 1

        startDate = DateSerial(startDate.Year, startDate.Month, startDate.Day - offset)
        stopDate = DateSerial(stopDate.Year, stopDate.Month, stopDate.Day - offset)

        res(2) = stopDate.Day - startDate.Day ' days
        res(1) = IIf(stopDate.Month >= startDate.Month, stopDate.Month - startDate.Month, stopDate.Month + 12 - startDate.Month) ' months
        res(0) = IIf(stopDate.Month >= startDate.Month, stopDate.Year - startDate.Year, stopDate.Year - 1 - startDate.Year) ' years

        Return res
    End Function

AnswerRe: Thanks (issue with leap year) ... Pin
xirc_za12-Mar-13 12:57
xirc_za12-Mar-13 12:57 
AnswerRe: Thanks [modified] Pin
MeenakshiLuthra22-Jan-12 22:37
MeenakshiLuthra22-Jan-12 22:37 
GeneralSmall correction Pin
acko0857-May-11 18:29
acko0857-May-11 18:29 
GeneralGood work - made few changes to make it more accurate Pin
Juvenile8-Dec-10 0:17
Juvenile8-Dec-10 0:17 
GeneralMy vote of 5 Pin
masterJalchr25-Nov-10 21:10
masterJalchr25-Nov-10 21:10 
GeneralHours, Mins, Seconds as well. Pin
Armoghan Asif23-Nov-10 5:26
Armoghan Asif23-Nov-10 5:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.