Parse Time

Does Xojo have a way to parse a string value to see if it is a valid time string? The following should be considered valid:

3:40 PM
3:40:12 PM
15:40
15:40:12

I’ve tried using the ParseDateMBS which almost works but it requires seconds to be present and if I put 3:40:00 PM it validates it as 3:40:00 AM so not sure how to work around that.

maybe DateTime.FromString with a try catch

my favorite command instead of regex is .Split
then use .ToInteger
if there is .Trim .EndsWith PM add 12 to hours

if you use a date time input control you not need to parse text.

Here is a dirty method which does the job

Then just call

datetimepicker1.SelectedDate = TextTimetoDateTime(textfield1.text)

var hour,minutes,seconds as integer 

var datearray() as string
datearray = texttime.split(":")

hour = datearray(0).tointeger
minutes = datearray(1).tointeger
try
  seconds = datearray(2).tointeger
exception
  seconds = 0
end try

if texttime.indexof("PM")  > 0 then hour = hour+12

var thedatetime as new datetime(2023,1,1,hour,minutes,seconds)

return thedatetime

Only when the hours is under 12. You don’t want to change 15 minutes past noon to 24 o’clock…

1 Like

I’m told that exceptions are expensive. Wouldn’t this be better/shorter:

seconds = if  (datearray.LastIndex>1,  datearray(2).tointeger, 0)
1 Like

Definitely. It’s just a dirty code.

Paste this into a constant, say kTimePattern:

(?x)
^

# Time like 3:45:56 PM or 12:01 AM
(
  # hour
  (1[012] | [1-9])  # 1 - 12
  # minutes with optional seconds
  (:[0-5]\d){1,2} # 00 - 59
  # space
  \x20
  # AM/PM
  [AP]M
)

| # or

# Military time
(
  # hour
  ([01]\d | 2[0-3]) # 00 - 23
  # minutes with optional seconds
  (:[0-5]\d){1,2} # 00 - 59
)

$

Then this code:

var rxTime as new RegEx
rxTime.SearchPattern = kTimePattern

if rxTime.Search( timeString ) isa RegExMatch then
  // It's valid
else
  // Not valid
end if
3 Likes