If you are looking for a DateDiff function in C# like in VB or SQL Server, there is none. However here are some options to perform date operations in .Net via C#.
Option 1
You can subtract two DateTime objects which returns a TimeSpan object. Here is an example:
//To get the amount of days between two dates. DateTime date1 = new DateTime(2007,1,1); DateTime date2 = DateTime.Today; int daysDiff = ((TimeSpan) (date2 - date1)).Days;
This is possible via operator overloading. Here are the MSDN docs on addition and subtraction.
Option 2
Write you own DateDiff function. Of course somebody already has. Just copy and paste.
Option 3
For VB fans, you can reference the Microsoft.VisualBasic dll and access the VB DateDiff function directly. See the example on this page.


Wed, Apr 1, 2009
Tech Tips