Hello Guys..

I am working in VB.NET
I have to textbox : txtStartTime and txtEndTime
After filling in values i need to validate that Start time must be less then Endtime. Values are entered in 12 hour format like
08:32 AM

I can go for sub string logic and split by : and all .. but that is old logic and tidy..
Can anyone give me function with some tricks which is short code???
Code will be Helpful:)
Thanks

Dani AI

Generated

— short, reliable way to solve this without brittle substring math: parse the two text values into DateTime objects with an exact format, validate the parse, then compare. pointed you toward parsing (good), and showed comparing numeric date values — the snippet below combines those ideas into a tidy, robust function that also handles cross‑midnight ranges when appropriate.

Imports System.Globalization

Function IsValidTimeRange(startText As String, endText As String) As Boolean
    Dim formats() As String = {"h:mm tt", "hh:mm tt"} ' accept 8:05 AM and 08:05 AM
    Dim s As DateTime, e As DateTime

    If Not DateTime.TryParseExact(startText.Trim(), formats, CultureInfo.InvariantCulture, DateTimeStyles.None, s) _
       OrElse Not DateTime.TryParseExact(endText.Trim(), formats, CultureInfo.InvariantCulture, DateTimeStyles.None, e) Then
        Return False ' invalid format
    End If

    s = DateTime.Today.Add(s.TimeOfDay)
    e = DateTime.Today.Add(e.TimeOfDay)

    ' treat an end time that is not after start as next-day end; change this if equal should be invalid
    If e <= s Then e = e.AddDays(1)

    Return s < e
End Function

Notes and tips: add more format strings (for example "h:mmtt" or "h:mm:ss tt") if you must accept inputs without a space or with seconds. If your business rule forbids overnight spans, remove the AddDays(1) logic and require e > s. Use a MaskedTextBox or DateTimePicker when possible to eliminate parsing errors entirely. Test edge cases such as "12:00 AM" vs "12:00 PM" to confirm the behavior you want.

This keeps the code short, avoids exceptions on bad input, and is easy to reuse in validation routines — building on the suggestions from , , and while addressing common pitfalls.

Recommended Answers

All 4 Replies

Something like

Convert.ToDateTime(txt1.Text) < Convert.ToDateTime(txt2.Text)

You can also use DateTime.TryParse()

Take a look at the datetime ToOADate method.

http://msdn.microsoft.com/library/de...ADateTopic.asp

It converts .NET DateTime format to Double. Since you converted your DateTime value to Double value you can compare them.

Hope this post helps you :icon_biggrin:

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.