Monday, January 31, 2011

Calculating Date Difference in C#

In this example we show two ways to calculate the difference between two dates:

            System.DateTime dt1 = new System.DateTime(2011, 1, 31, 12, 0, 0);

            System.DateTime dt2 = new System.DateTime(2011, 2, 30, 12, 0, 0);

            // Option One
            System.TimeSpan diff = dt1  - dt2;

            // Option two
            System.TimeSpan diff = dt1.Subtract(dt2);

            Console.WriteLine("Diff in days " + diff.Days);

            Console.WriteLine("Diff in total days " + diff.TotalDays);

            Console.WriteLine("Diff in hours " + diff.Hours);

            Console.WriteLine("Diff in minutes " + diff.Minutes);

            Console.WriteLine("Diff in seconds" + diff.Seconds);

No comments:

Post a Comment