Difference between dates

Having 30 Aug 2012 19:15:00 and 30 Aug 2012 19:15:45 how can I calculate the difference between the two dates in the format hh:mm:ss
I'm having trouble getting the date recognised as a date to do the datetime.parse.

Thanks
LVL 58
GaryAsked:
Who is Participating?
 
Mike TomlinsonConnect With a Mentor Middle School Assistant TeacherCommented:
You'll need to use DateTime.TryParseExact(), and specify a culture of English so it can recognize the short forms of the months.  Also note that the maximum value that can be returned by the Hours() property is 23 so if the difference is greater than that you'll need to include the Days() property into your format:
        Dim strDtA As String = "30 Aug 2012 19:15:00"
        Dim strDtB As String = "30 Aug 2012 19:15:45"

        Dim DtA, DtB As DateTime
        Dim English As New System.Globalization.CultureInfo("en-US")
        Dim AllowedFormats() As String = {"d MMM yyyy H:mm:ss", "dd MMM yyyy H:mm:ss", "d MMM yyyy HH:mm:ss", "dd MMM yyyy HH:mm:ss"}

        If DateTime.TryParseExact(strDtA, AllowedFormats, English, Globalization.DateTimeStyles.None, DtA) Then
            If DateTime.TryParseExact(strDtB, AllowedFormats, English, Globalization.DateTimeStyles.None, DtB) Then
                Dim TS As TimeSpan = DtB.Subtract(DtA)
                Dim strTimeSpan As String = String.Format("{0}:{1}:{2}", TS.Hours.ToString("00"), TS.Minutes.ToString("00"), TS.Seconds.ToString("00"))
                MessageBox.Show(strTimeSpan, "Duration")
            Else
                MessageBox.Show(strDtB, "Invalid Stop Date")
            End If
        Else
            MessageBox.Show(strDtA, "Invalid Start Date")
        End If

Open in new window

0
 
David Johnson, CD, MVPOwnerCommented:
Is it a string or a date object? you might have to do the conversion.
0
 
GaryAuthor Commented:
Works great, thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.