Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to check if a string is a valid time?

I'm pulling data from a feed that I have no control over and I need to verify if a string I'm given is a valid time.

Most of the time I'm correctly sent something like "2:35" or "15:41" but other times it's things like "AM" or "PM" (and no numbers)...so I ultimately just need to ignore those.

So, how can I verify if the data is a valid time?

like image 819
Shpigford Avatar asked May 11 '10 13:05

Shpigford


2 Answers

You haven't exactly specified what you assume to be a valid time (e.g. whether you should accept optional seconds), so here's one guess:

data =~ /^([01]?[0-9]|2[0-3])\:[0-5][0-9]$/
like image 149
Mladen Jablanović Avatar answered Sep 30 '22 14:09

Mladen Jablanović


Using Time.parse() is not a good solution, as shown in the example of the comments.

I'll leave the answer here for 'historical reasons', to keep the comments, and as a warning for future readers!


You can use Time.parse() and check for the ArgumentError exception for invalid times.

Extra advantage is that you also have the time in a usable format to work with if it is valid!

like image 44
Veger Avatar answered Sep 30 '22 15:09

Veger