locked
DateDiff function in VB.Net

    Question

  • Dim firstDate1 As String = "01/28/1964"  
    Dim SecondDate1 As String = "12/21/1866"   
    Dim years1 As Integer = DateDiff(DateInterval.Year, CDate(SecondDate1), CDate(firstDate1))  
       
    Dim firstDate2 As String = "08/14/1970"  
    Dim SecondDate2 As String = "02/02/1873"   
    Dim years2 As Integer = DateDiff(DateInterval.Year, CDate(SecondDate2), CDate(firstDate2))
    See the Result
            Value of years1 = 98
            If you calculate difference manually, you will find the difference between firstDate1 and SecondDate1 = 97 years 1 month 7 days


            Value of years2 = 97
            If you calculate difference manually, you will find the difference between firstDate2 and SecondDate2 = 97 years 6 month 12 days

            You can see the that first difference is smaller than second. But Datediff function gives the result just opposite.

           Can any one explain me about these result?

    Hirendra

    Wednesday, May 16, 2012 8:43 AM

Answers

  • 1964 - 1866 = 98
    1970 - 1873 = 97

    An alternative method of calculating the year difference is to calculate a timespan and then round that result to a number of years according to your selected rounding rule.

    Wednesday, May 16, 2012 10:37 AM
  • OK, lets make it blunt: don't use DateDiff.

    You can add and subtract dates to and from one another giving you a timespan object.


    Stephen J Whiteley

    Wednesday, May 16, 2012 3:31 PM

All replies

  • 1964 - 1866 = 98
    1970 - 1873 = 97

    An alternative method of calculating the year difference is to calculate a timespan and then round that result to a number of years according to your selected rounding rule.

    Wednesday, May 16, 2012 10:37 AM
  • Acamar is correct, and your result is correct: DateDiff is simply looking at the years, and no rounding is taking place. DateDiff is a 'legacy' function from VB6 days, and replicates what DateDiff did way back then, and doesn't reflect necessarily what one would expect.


    Stephen J Whiteley

    Wednesday, May 16, 2012 12:35 PM
  • Right..

    now i am using this function as:

    Dim years1 as integer = Math.Round((DateDiff(DateInterval.Day, CDate(txtDob.Text), CDate(txtDod.Text)) / 365))

    Thanks


    Hirendra Sisodiya from authorcode.com

    Wednesday, May 16, 2012 12:57 PM
  • OK, lets make it blunt: don't use DateDiff.

    You can add and subtract dates to and from one another giving you a timespan object.


    Stephen J Whiteley

    Wednesday, May 16, 2012 3:31 PM