Get date difference in VB.NET

Viewed 86593

I want to get the difference between two dates chosen by two date time pickers in years, months & days in separate text boxes.

I've tried:

txtyrs.text = datediff(datetimepicker1,datetimepicker2)

It is not working.

10 Answers

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.

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

I've created this function with optional EndDate with default the current one. I've added the zero function to the time.

Public Shared Function Zero(ByVal Number As Integer) As String
    If Number < 10 Then
        Return "0" & Number.ToString
    Else
        Return Number.ToString
    End If
End Function

Public Shared Function TimeDifference(ByVal StartDate As DateTime, Optional ByVal EndDate As DateTime = Nothing) As String
    If EndDate = Nothing Then
        EndDate = Date.Now()
    End If
    Dim timediff As TimeSpan
    If EndDate > StartDate Then
        timediff = EndDate - StartDate
        Return timediff.Days & ":" & Zero(timediff.Hours) & ":" & Zero(timediff.Minutes) & ":" & Zero(timediff.Seconds)
    Else
        timediff = StartDate - EndDate
        Return timediff.Days & ":" & Zero(timediff.Hours) & ":" & Zero(timediff.Minutes) & ":" & Zero(timediff.Seconds)
    End If
End Function
Related