• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 487
  • Last Modified:

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.

1 Solution
Mike TomlinsonMiddle 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")
                MessageBox.Show(strDtB, "Invalid Stop Date")
            End If
            MessageBox.Show(strDtA, "Invalid Start Date")
        End If

Open in new window

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

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now