Condividi tramite


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

  • Anonymous
    May 30, 2004
    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.

  • Anonymous
    May 30, 2004
    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?

  • Anonymous
    May 30, 2004
    The comment has been removed

  • Anonymous
    May 30, 2004
    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.

  • Anonymous
    May 31, 2004
    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.

  • Anonymous
    June 05, 2004
    The comment has been removed

  • Anonymous
    July 01, 2004
    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

  • Anonymous
    July 06, 2004
    How do I calculate the total number seconds between two DateTimes in C#???

  • Anonymous
    July 06, 2004
    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);

  • Anonymous
    January 20, 2009
    PingBack from http://www.hilpers-esp.com/434541-como-saber-cuantos-mese-hay

  • Anonymous
    January 21, 2009
    PingBack from http://www.hilpers.it/1715880-numero-giorni

  • Anonymous
    June 02, 2009
    PingBack from http://uniformstores.info/story.php?id=41998