How to Compare Time in Visual Basic

How to Compare Time in Visual Basic thumbnail
You can compare two time variables in Visual Basic.

Creating time management functions in your Visual Basic application involves comparing time variables. You can compare two time variables and execute code dependent on a certain condition. If both variables in the Visual Basic application are the "Date" or "Time" type, then the compiler automatically knows that the comparison should be for minutes, hours or days. Comparing times involves setting up the variables and placing them in an "If" statement.

Instructions

    • 1

      Open your Visual Basic project. When the project loads, double-click the form you want to edit in the Solution Explorer. When the form loads, right-click it and select "Code View." This opens your code-behind file.

    • 2

      Create two time variables. These variables will be used to compare the time and execute code. The code below creates two time variables:

      Dim StartDate as String
      Dim EndDate as String
      StartDate = "1:00 PM"
      EndDate = "2:00 PM"

    • 3

      Compare the two dates. The DateTime class contains a compare function you can use to compare the time. The code below illustrates how to compare the two variables created:

      If DateTime.Compare(StartDate, EndDate) < 0 Then
      MsgBox "The Start Date is less than the End Date"
      Else
      MsgBox "The End Date is less than the Start Date"

      The code above prints a message advising the user which date is smaller.

    • 4

      Save the file and press the F5 key. This runs the code in the compiler debugger, so you can test the new block of code.

Related Searches:

References

  • Photo Credit time image by Jaroslav Machacek from Fotolia.com

Comments

You May Also Like

Related Ads

Featured