views:

63

answers:

2

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?

+1  A: 

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]$/
Mladen Jablanović
although Time.parse() with a rescue can work, I'd prefer the regex solution. Exceptions in ruby aren't considered really fast, so unless you need the time object, this is the advice I'd go with.
Dan Frade
Using regex brings problems on its own: lots of different time formats making in very complicated to check whether the given time is valid. When you want to support all/most possible time formats you're basically reimplementing the `Time.parse()` method...
Veger
All depends how strict you like to be when accepting values. I presumed maximum strictness (only optional thing being a leading zero in hours). The question doesn't specify. In addition to that, `Time.parse` seems to be really really liberal when it comes to arguments. Try, for example: `Time.parse '10'` and `Time.parse 'asd'`. Neither throws an exception (at least in 1.9.1). I really wouldn't rely on it.
Mladen Jablanović
+4  A: 

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!

Veger