Posted By

hnielsen on 10/08/09


Tagged

DateTime


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

rtipton


DateTime difference


 / Published in: C#
 

Calculates the years, months and days between two DateTime objects

  1. public static void TimeSpanToDate(DateTime larger, DateTime smaller, out int years, out int months, out int days)
  2. {
  3. // we want larger to be the larger (newest) date
  4. // flip if we need to
  5. if (larger < smaller)
  6. {
  7. DateTime d3 = smaller;
  8. smaller = larger;
  9. larger = d3;
  10. }
  11.  
  12. // compute difference in total months
  13. months = 12 * (larger.Year - smaller.Year) + (larger.Month - smaller.Month);
  14.  
  15. // based upon the 'days',
  16. // adjust months & compute actual days difference
  17. if (larger.Day < smaller.Day)
  18. {
  19. months--;
  20. days = DateTime.DaysInMonth(smaller.Year, smaller.Month) - smaller.Day + larger.Day;
  21. }
  22. else
  23. {
  24. days = larger.Day - smaller.Day;
  25. }
  26. // compute years & actual months
  27. years = months / 12;
  28. months -= years * 12;
  29. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: nvesic on August 20, 2010

The alghoritm is not quite correct. For example difference between 31/3/2010 and 30/4/2010 is o months and 30 days, and clearly should be 1 monh and 0 days. I have made version in which this "bug" is solved, but I don't know how to upload it.

You need to login to post a comment.