DateTime difference


/ Published in: C#
Save to your folder(s)

Calculates the years, months and days between two DateTime objects


Copy this code and paste it in your HTML
  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

You need to login to post a comment.