C# difference between two dates in years, months and days

One of the most challenging thing in Software is manipulating with the DateTime function, like converting one date to a different date timezone and finding the difference between dates and many more. In this tutorial, I will show you how to find the difference between the two dates.

using System;
using System.Collections.Generic;
using System.Text;

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

    class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = new DateTime(1994, 12, 12);
            DateTime dt2 = new DateTime(1994, 12, 12);
            long date = DateDiff(DateInterval.Day, dt1, dt2);
            Console.Write(date);

            Console.ReadLine();
        }



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

            TimeSpan ts = 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);
        }
    }
}

Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru