DateDiff Equivalent in C# – 3 Options

Wed, Apr 1, 2009

Tech Tips

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.

Bookmark and Share
, ,

3 Responses to “DateDiff Equivalent in C# – 3 Options”

  1. Joe P Says:

    You must reference System.Data.Linq

    DateTime startDT = DateTime.Now.AddYears(5);
    DateTime endDT = DateTime.Now.AddYears(8);
    int monthDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(startDT, endDT);
    int dayDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffDay(startDT, endDT);
    int yearDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffYear(startDT, endDT);
    int minDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMinute(startDT, endDT);
    int secDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffSecond(startDT, endDT);
    int hrsDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffHour(startDT, endDT);
    int msDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMillisecond(startDT, endDT);

  2. Joe P Says:

    You must reference System.Data.Linq

    DateTime startDT = DateTime.Now.AddDays(5);
    DateTime endDT = DateTime.Now.AddDays(8);
    int monthDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMonth(startDT, endDT);
    int dayDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffDay(startDT, endDT);
    int yearDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffYear(startDT, endDT);
    int minDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMinute(startDT, endDT);
    int secDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffSecond(startDT, endDT);
    int hrsDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffHour(startDT, endDT);
    int msDiff = System.Data.Linq.SqlClient.SqlMethods.DateDiffMillisecond(startDT, endDT);

  3. Raj Says:

    If you want the exact DateDiff function as it works in SQL, you can remove time stamp of the Date variables and then Subtract one from another. It will give u exact number of days. Ex.

    DateTime dt = DateTime.Parse(fromDate.ToShortDateString());
    DateTime dt1 = DateTime.Parse(toDate.ToShortDateString());

    int noOfDays = dt.Subtract(dt1).TotalDays;