DateDiff() function in C#

By Fons Sonnemans, 11-2-2004

I have written the following DateDiff() function in C#. VB.NET users already had it using the Micrsoft.VisualBasic.dll assembly. Now you can use it without referencing this 'ugly' extra assembly.

using System;


namespace ReflectionIT.System {

    public enum DateInterval {
        Year,
        Month,
        Weekday,
        Day,
        Hour,
        Minute,
        Second
    }

    public class DateTimeUtil {

        public static long DateDiff(DateInterval interval, DateTime date1, DateTime date2) {

            TimeSpan ts = date2 - date1;

            switch (interval) {
                case DateInterval.Year:
                    return date2.Year - date1.Year;
                case DateInterval.Month:
                    return (date2.Month - date1.Month) + (12 * (date2.Year - date1.Year));
                case DateInterval.Weekday:
                    return Fix(ts.TotalDays) / 7;
                case DateInterval.Day:
                    return Fix(ts.TotalDays);
                case DateInterval.Hour:
                    return Fix(ts.TotalHours);
                case DateInterval.Minute:
                    return Fix(ts.TotalMinutes);
                default:
                    return Fix(ts.TotalSeconds);
            }
        }

        private static long Fix(double Number) {
            if (Number >= 0) {
                return (long)Math.Floor(Number);
            }
            return (long)Math.Ceiling(Number);
        }
    }
}


Leave a Comment

Leave a Comment
Name
Comment
7 + 8 =

4 Comments

  • Marco Pellicciotta
    30 jan 2014 08:32
    Marco Pellicciotta: After using it a few times a see a bug and I want to report. The fix function must be: private static long Fix(double Number) { if (Number >= 0) { return (long)Math.Ceiling(Number); } return (long)Math.Floor(Number); } } Just change Ceiling by Floor.
  • Marco Pellicciotta
    13 nov 2013 04:46
    The trick is with month values, because TimeSpan do not give you the difference of months.
  • Marco Pellicciotta
    13 nov 2013 04:35
    Exactly what I was looking for. Thanks!
  • Raj
    6 mei 2013 08:48
    If you want the exact DateDiff function as it works in SQL, you can remove time stamp of the Date variables and then Subtract one from another. It will give u exact number of days. Ex. DateTime dt = DateTime.Parse(fromDate.ToShortDateString()); DateTime dt1 = DateTime.Parse(toDate.ToShortDateString()); int noOfDays = dt.Subtract(dt1).TotalDays;

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.