compare two times in 24-hour format

cwt

Member
Licensed User
I need to compare two times in 24-hour format.

The times are in string variables such as:

StartTime = "17:45"
EndTime = "19:00"

I need to check if EndTime is < StartTime.

How would I convert the string "17:45" and the string "19:00" to Long variables so I can compare which time is the earliest?

What I want to do is prevent the user from entering an EndTime that is earlier than the StartTime.

The EndTime can be zero but if it is set it cannot be earlier than the StartTime.

If EndTime > 0 And EndTime < StartTime Then
'stop right there
End If

I am using TimeDialog to set the StartTime and EndTime

Thanks
 
Last edited:

admac231

Active Member
Licensed User
I would say the simplest way would be to change the colon to a period, converting to a long (b4a converts string to long for you)

B4X:
Dim strStartTime As String
Dim strEndTime As String
Dim lngStartTime As Long
Dim lngStartTime As Long
strStartTime = "17:45"
strEndTime = "19:00"

lngStartTime = strStartTime.Replace(":",".")
lngEndTime = strEndTime.Replace(":",".")
 

thedesolatesoul

Expert
Licensed User
Another way is to convert the Time to Long (ticks) and then do a compare.

B4X:
DateTime.TimeFormat="HH:mm"
Dim StartTimeTicks As Long 
StartTimeTicks =  DateTime.TimeParse(StartTime)
Dim EndTimeTicks As Long 
EndTimeTicks =  DateTime.TimeParse(EndTime)
If EndTimeTicks < StartTimeTicks Then
'Do something
End If
 

DouglasNYoung

Active Member
Licensed User
Even easier is just compare the two strings! Presumable the EndTime of 0 indicates an empty value which ought to be set by the program say as "0", or any other value which precedes "00:00".

Then:

B4X:
If EndTime.CompareTo( "0" ) > 0 and  EndTime.CompareTo( StartTime ) < 0 Then
  'End time set and endtime before start time!
  'stop right there
End If
Don't know what the application is, but what happens if start is before midnight and stop is after midnight - If that is a possibility then the 'ticks' solution might be best; although a date&time string in the form of 'YYYYMMDDhhmmss' would work, and has the advantage of being human readable.

Cheers,
Douglas
 

cwt

Member
Licensed User
The "ticks" solution will not work for me because the times I am comparing are all relative to the same day - meaning starting at midnight. Thus 11:00PM would be less than 1:00AM, 2 hours later.

I think Admac231's solution will work best - replacing ":" with "."

Thanks all
 

lagore

Active Member
Licensed User
The ticks solution will work because when you time parse in B4A it uses the current date to calculate the ticks to give a meaningful ticks from epoch, otherwise it would only be giving ticks from midnight. So any time parse done on the same day will always give ticks/times relative to each other thus 1:00am < 11:00pm.
 
Top