Get Date Difference in C#
by Victor | March 20, 2008 in C# | No Comments
To get the difference between two dates in C# is easy given the built in functions. The method requires two DateTime variables. In the example below, we will calculate the difference between two string dates.
string startDateString = "1/10/2006"; string endDateString = "3/24/2007"; DateTime startDate = Convert.ToDateTime(startDateString); DateTime endDate = Convert.ToDateTime(endDateString); TimeSpan dateDifference = endDate.Subtract(startDate); int days = dateDifference.Days;
In the example above, two random dates are assigned to strings (startDateString and endDateString). The ToDateTime function of the Convert class is utilized to convert both strings into type DateTime. Finally, the subtract function is called on the future date and the result passed to the TimeSpan class. With the TimeSpan class, the difference in days, hours, milliseconds, minutes, and seconds can be determined. Our example above example is days.
More specifically, the TimeSpan class is capable of returning to either full integers as days, hours, milliseconds, minutes, and seconds. The second option is to return as doubles full and partial days, hours, milliseconds, minutes, and seconds. Additionally, this process will work with the full DateTime format.




