Click here to Skip to main content
6,936,634 members and growing! (20,533 online)
Email Password   helpLost your password?
 
General Programming » Date and Time » General     Intermediate License: The Code Project Open License (CPOL)

Calculate Difference Between Two Dates in Day, Week, Month, and Year Parts

By Mahmoud Fathy Afify

Calculate difference between two dates in day, week, month, and year parts.
C#, .NET, Dev
Revision:4 (See All)
Posted:19 Nov 2009
Updated:22 Nov 2009
Views:5,485
Bookmarked:26 times
printPrint Friendly   add Share
      Discuss Discuss   Broken Article?Report  
12 votes for this article.
Popularity: 4.93 Rating: 4.57 out of 5

1

2
2 votes, 16.7%
3
1 vote, 8.3%
4
9 votes, 75.0%
5

Date_Diff_demo

Introduction

During my investigation of the DateTime and TimeSpan classes, I faced the following question several times, and unfortunately, I didn't find an answer to it.

How can I get the difference between two dates in number of days, weeks, months, and years? I tried to use the Subtract method of the DateTime class, and it gave me the difference in TimeSpan, from which I can get the duration in days, hours, and so on... but how can I get the difference in larger date parts?

I found it a very common requirement to display the date difference between two dates with high precision, considering leap years and the number of days in each month.

So I decided to write my own library (DateCalculator_Lib) which provides to its user a complete set of properties for all required date parts (days, weeks, months, years) along with some extra properties like number of leap years and a collection containing the accrual of each month during the difference period, and a group of properties representing each date part total accrual in the difference period, like total number of days, months,......etc.

Using the Code

All you need is to add a reference to DateCalculator.dll in your .NET project and the using statement for the DateCalculator namespace, then create an object from the DateCalculator class which will need the start and end dates in its constructor.

After that, just call the public CalculateDateDifference method from your object, and it will calculate each date difference part and assign it to the appropriate property.

Use those read only properties to retrieve all your needs....

The attached demo project contains all the previously explained steps.

//Add the using statement 
using DateCalculator;

private void button1_Click(object sender, EventArgs e) 
{ 
    //create the object 
    DateCalculator.DateCalculator DC = new DateCalculator.DateCalculator
    ( this.dateTimePicker1.Value, this.dateTimePicker2.Value); 

    //call the method 
    DC.CalculateDateDifference(); 
    // use the read only properties
    this.day_txt.Text = DC.Days.ToString(); 
    this.week_txt.Text = DC.Weeks.ToString(); 
    this.month_txt.Text = DC.Months.ToString(); 
    this.year_txt.Text = DC.Years.ToString(); 
}

Algorithm Explanation

This library depends on a well known algorithm called "Goal Seek" algorithm; we start from the "Start Date" and go on until we reach the "End Date", which is our goal...during the journey, we collect information by accumulating days and months and leap years inside the period between the start and end dates.

The algorithm depends on a container "Integer array" that contains the number of days in each month except February, as this month is the differentiator between normal and leap years.

And the algorithm logical steps are as follows:

  1. If our Goal -->>"End date" is not reached, continue.
  2. Check if current month is February or not, and accumulate days and months.
  3. Update the public properties.
  4. Check the termination condition "Did we reach the goal or not".
  5. If not, get the next month index and continue in the loop.
  6. If we exceed the goal, we seek it by going forward and backward until we stop on the end date.

Finally, after finishing this loop, all public properties will contain the accumulated information collected through the cycle.

History

  • 19th November, 2009: Initial post.

License

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

About the Author

Mahmoud Fathy Afify


Member
our work represents us
Occupation: Software Developer
Company: International TurnKey Systems (ITS)
Location: Egypt Egypt

Other popular Date and Time articles:

 
Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 2 of 2 (Total in Forum: 2) (Refresh)FirstPrevNext
GeneralWhy not... Pinmemberkasparovthe23:19 20 Nov '09  
GeneralRe: Why not... PinmemberMahmoud Fathy Afify23:00 21 Nov '09  
Because DateTime.Subtract() only gives you the difference in term of number of days, but if your needs requires more specific level of details like "How many leap years in this period?", or "What is the total number of weeks months and years are represented by this time period?" , or "How many number of occurance of November??" also the main idea is about getting the date difference in more usable form.... imagin thie case when i ask you the following question "What is the difference between 13/2/2005 and todays Date?" and the reply is 1743 days or 4 years, 9 months,1 week and 2 days Wink

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

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

PermaLink | Privacy | Terms of Use
Last Updated: 22 Nov 2009
Editor: Smitha Vijayan
Copyright 2009 by Mahmoud Fathy Afify
Everything else Copyright © CodeProject, 1999-2010
Web10 | Advertise on the Code Project