top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to substract two dates in C#?

+1 vote
469 views
How to substract two dates in C#?
posted Jun 23, 2017 by Pooja Bhanout

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button
Assuming StartDate and EndDate are of type DateTime:

(EndDate - StartDate).TotalDays

1 Answer

+1 vote

various options for calculating the date difference in C#.
* DateTime Structure: This datatype is used to represent a time instant in C#
* TimeSpan Structure: The TimeSpan datatype is used to represent time interval
Calculating the Date Difference - Subtract Method

The DateTime.Substract method may be used in order to find the date/time difference between two instances of the DateTime method. This method does not change the value of the DateTime instance on which the method has been invoked. The result of the operation is stored in the new TimeSpan structure.

The TimeSpan class has a dual set of properties, one set represents the time durations in integers and another set of properties, with the names prefixed with "Total" represents the result in fractional values. The following sample code illustrates the use of the DateTime.Subtract method and the Days and TotalDays properties of the TimeSpan structure.

The TimeSpan structure has additional properties for the Hours, Minutes, Seconds and Milliseconds and for TotalHours, TotalMinutes, TotalSeconds and TotalMilliseconds.

The DateTime structure also has an overload for the Subtract method which accepts a TimeSpan and returns the DateTime value which is the result of subtracting the Timespan argument from the value of the DateTime structure on which the Subtract method has been invoked.

Code Sample: Calculating the Date Difference - Subtract Method.

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

namespace Console_DateTime
{
    class Program
    {
        static void Main(string[] args)
        {
            System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);
            System.DateTime dtTodayMidnight = new System.DateTime(2006, 9, 13, 0, 0, 0);
            System.TimeSpan diffResult = dtTodayNoon.Subtract(dtYestMidnight);
            Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);
            Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);
            Console.ReadLine();
        }
    }
}

Image: Results for Calculating the Date Difference - Subtract Method.

enter image description here

Calculating the Date Difference - Subtraction Operator

A more intuitive method for calculating the Date Difference is through the use of the Subtraction Operator (the minus sign). The following code sample yields the same result as the first code sample using the Subtract Method.

Code Sample: Calculating the Date Difference - Subtraction Operator.

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

namespace Console_DateTime
{
    class Program
    {
        static void Main(string[] args)
        {
            System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);
            System.DateTime dtYestMidnight = new System.DateTime(2006, 9, 12, 0, 0, 0);
            System.TimeSpan diffResult = dtTodayNoon - dtYestMidnight;
            Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);
            Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);
            Console.ReadLine();
        }
    }
}

DateDiff Function

A third alternative for date subtraction in C# is by importing the Microsoft.VisualBasic namespace and invoking the DateDiff method. Opponents of this technique offer the critique that importing the namespace involves extra weight. Proponents of the technique provide contradictory arguments.

If the requirements are only restricted to calculating a basic date difference, the direct use of the DateTime structure is recommended.

Impact of TimeZones

The techniques described above do not take factors such as TimeZone and Daylight Savings Time into account. The operations assume that both the date arguments have been converted to the same time zone before the operation is invoked.

Impact of DayLight Savings Time

If the date calculations are performed in a locale involving Daylight Savings Time, an additional step is required to convert the DateTime object values to Universal Time by using the ToUniversalTime method.

System.TimeSpan diffResult = dtTodayNoon.ToUniversalTime().Subtract(dtYestMidnight.ToUniversalTime());
answer Jun 26, 2017 by Shivaranjini
...