Yogesh Jagota's Personal Blog
small c# code snippets and free code libraries

Calculating difference between two dates

Thursday, 31 January 2008 18:04 by Yogesh Jagota

I have seen many c# programmers searching for a VB.Net DateDiff function in c#. It can be done something like this:

   1:  // Quit self explanatory...
   2:  public class DateSpan
   3:  {
   4:      public int Days { get; set; }
   5:      public int Months { get; set; }
   6:      public int Years { get; set; }
   7:  }
   8:   
   9:  public static DateSpan DateDifference(this DateTime date, DateTime
  10:      dateToCompare)
  11:  {
  12:      // First we calculate total months
  13:      int totalMonths = ((date.Year - dateToCompare.Year) * 12) +
  14:          date.Month - dateToCompare.Month;
  15:   
  16:      int days = 0;
  17:   
  18:      // A month completes on one day before the exact day of the
  19:      // actual date. For example, if starting date is 15-Mar, one 
  20:      // month will complete on 14-Apr regardless of how many days
  21:      // are present in march.
  22:      // So, this is the code to do the same...
  23:      if (date.Day < dateToCompare.Day)
  24:      {
  25:          int day, month, year;
  26:   
  27:          day = dateToCompare.Day;
  28:   
  29:          // If month is jan, switch to dec
  30:          if (date.Month == 1)
  31:          {
  32:              month = 12;
  33:              year = date.Year - 1;
  34:          }
  35:          else
  36:          {
  37:              month = date.Month - 1;
  38:              year = date.Year;
  39:          }
  40:   
  41:          DateTime dateCalculator = new DateTime(year, month, day);
  42:   
  43:          days = (date - dateCalculator).Days;
  44:   
  45:          totalMonths--;
  46:      }
  47:      else
  48:      {
  49:          days = date.Day - dateToCompare.Day;
  50:      }
  51:   
  52:      DateSpan ds = new DateSpan();
  53:      ds.Years = totalMonths / 12;
  54:      ds.Months = totalMonths % 12;
  55:      ds.Days = days;
  56:   
  57:      return ds;
  58:  }


Quite simple as I think of it. Calculating time is not very difficult either, but more on that later. 

Del.icio.usDigg It!DZone It!kick it on DotNetKicks.com
Tags:   ,
Categories:   C# | General
Actions:   E-mail | Permalink | Comments (3) | Comment RSSRSS comment feed

Comments

Add comment


 

biuquote
Loading