How do I determine the difference between two dates?


Posted by: Duncan Mackenzie, MSDN
This post applies to Visual Basic .NET 2002/2003


This common question is often phrased as “How do I find the number of hours between two dates?”, substituting minutes, seconds, days, or whatever interval you are looking for in the place of ‘hours’. Well, in Visual Basic .NET there are two main ways to achieve this result; the DateDiff function or through the TimeSpan structure.


Both of these methods are equally valid, where they overlap in functionality, but each of them has a couple of unique features.  Despite their similar functions, the core difference between the two is that DateDiff is a function, so you need to call it every time you need to retrieve a value, whereas TimeSpan is a structure that is created once and then you just work with its various members as needed.


Using DateDiff, you call it with different date interval parameters to retrieve the appropriate value:

        Dim D1, D2 As Date
        D1 = Date.Now
        D2 = #11/9/2004#
       
‘DateDiff
        Console.WriteLine(“DateDiff”)
        Console.WriteLine()
        Console.WriteLine(
“{0} Days”, _
           
DateDiff(DateInterval.Day, D1, D2))
        Console.WriteLine(
“{0} Hours”, _
           
DateDiff(DateInterval.Hour, D1, D2))
        Console.WriteLine(
“{0} Minutes”, _
           
DateDiff(DateInterval.Minute, D1, D2))
        Console.WriteLine(
“{0} Seconds”, _
           
DateDiff(DateInterval.Second, D1, D2))
        Console.WriteLine()
Alternatively, a TimeSpan structure can be retrieved as the result of subtracting one date from another, and then querying the various members of that structure.
        ‘TimeSpan
        Console.WriteLine(“TimeSpan”)
        Console.WriteLine()
       
Dim difference As TimeSpan = D2.Subtract(D1)
        Console.WriteLine(
“{0} Days”, difference.TotalDays)
        Console.WriteLine(
“{0} Hours”, difference.TotalHours)
        Console.WriteLine(
“{0} Minutes”, difference.TotalMinutes)
        Console.WriteLine(
“{0} Seconds”, difference.TotalSeconds)
        Console.WriteLine()

The output of the two different methods is nearly identical, except that the TimeSpan properties are returning Doubles, while DateDiff always returns Longs (Int64).


DateDiff


175 Days
4222 Hours
253345 Minutes
15200730 Seconds


TimeSpan


175.934383644387 Days
4222.42520746528 Hours
253345.512447917 Minutes
15200730.746875 Seconds


The fractional values returned from the TimeSpan properties are more meaningful that they might seem at first glance; each of these properties is returning the complete difference between the two dates, whereas the whole numbers returned from DateDiff only provide a value to within one interval (day, hour, etc…). Using only one of these properties from TimeSpan, it would be possible to figure out any other time interval (with varying degrees of precision, of course), although that calculation would seldom be required in practice.


The TimeSpan structure provides additional members (.Hours, .Days, etc…) that return values closer to what you see from DateDiff, so you can use those if it is more suitable for your situation. While TimeSpan can appear to have more features and to be more efficient, DateDiff has two benefits that may cause you to continue to use it in your Visual Basic .NET applications:



  1. It provides several date intervals that are not covered by TimeSpan, including Weeks and Quarters, and
  2. It is compatible with the VB6 function of the same name, allowing you to more easily reuse existing code.

Read the corresponding documentation for more information, but I hope that this has been helpful…



Comments (12)

  1. James Hancock says:

    Now what would be more interesting is finding the number of months (in a specified calendar) between two dates. Ditto for years. VB6 did this, .net doesn’t. BIG GOOF LEAVING THIS OUT.

  2. James….

    Console.WriteLine("{0} Years", _

    DateDiff(DateInterval.Year, D1, D2))

    Console.WriteLine("{0} Months", _

    DateDiff(DateInterval.Month, D1, D2))

    Doesn’t that do what you want?

  3. James Hancock says:

    Works great… in VB. Doesn’t work great in anything else .net unless you include the VB6 legacy stuff, and I don’t feel like doing that in my apps. (Yes, I know this is a blog about VB, but this should be part of the .net framework, not a backwards compatiblity hack.)

  4. DateDiff is not part of the VB6 legacy stuff, it is part of the VB language and part of Microsoft.VisualBasic.dll. My honest feeling on this is that if you like the features that VB gives you, you should use VB.NET… you’d be happier with it. Perhaps the goof was choosing to use a different .NET language when you are obviously used to the features of VB?

    Should it have been part of the Framework? No idea, but it is not in any way a backwards compatibility feature. There are classes provided in VB for legacy support, but this is not one of them.

    Many people have discussed this before, but the Microsoft.VisualBasic.Compatibility.dll is something that I can understand you would want to avoid, but Microsoft.VisualBasic.dll does not fall into the same category.

  5. James Hancock says:

    Unsafe code blocks.

    thus C#

    Finding the number of months and years between two dates is BASIC stuff for any language that wants to be used for anything to do with accounting, inventory management, or numerous other things.

    Result: BIG GOOF LEAVING THIS OUT.

  6. Cory Smith says:

    The Microsoft.VisualBasic namespace is shipped as a STANDARD PART of the Microsoft implementation of the .NET Framework Class Libraries. It’s on *EVERY* machine that the framework is installed upon. These functions are available to *ALL* languages that wish to reference the dll. IT IS A PART OF THE .NET FRAMEWORK… so… your "Big Goof Leaving This Out" is totally wrong.

    The Microsoft.VisualBasic.Compatiblity, as Duncan already stated, is NOT to be confused with Microsoft.VisualBasic. They are two completely different files and the Compatibility one is not automatically installed with the .NET Framework redistributable.

    Question? Are you willing to use code/component libraries from companies such as Desaware, Dart, Infragistics and ComponentOne? Does it matter what language these originally target (or even written in) if they can be utilized in your language of choice? If it improves your overall productivity the cost of those products is not an issue. What you are failing to see is that there’s an excellent library included within the .NET Framework that you are unwilling to even consider simply because it has the VisualBasic label on it.

    What you also need to understand, what is in the current version of Microsoft.VisualBasic is nothing in comparison to what will be in the next version…

  7. how to find the present age as on date .date diff is to be used toaday’s date – date of birth

    kindly let me know

  8. Tom Gross says:

    How do I calculate the total number seconds between two DateTimes in C#???

  9. Tom, did you read the post? The syntax is a little different, but the technique is exactly the same

    TimeSpan difference = D2.Subtract(D1);

    Console.WriteLine("{0} Seconds", difference.TotalSeconds);