diff --git a/README.markdown b/README.markdown index 629b3ba..4edae76 100644 --- a/README.markdown +++ b/README.markdown @@ -46,6 +46,15 @@ are all optional. Tod::TimeOfDay.parse "151253" # => 15:12:53 Tod::TimeOfDay.parse "noon" # => 12:00:00 Tod::TimeOfDay.parse "midnight" # => 00:00:00 + +Strings recognized as being in 24H format may optionally use any non-numeric +character(s) as separators. (A string will be treated as 24H format unless it +terminates with a meridian indicator) + + Tod::TimeOfDay.parse "2300" # => 23:00:00 + Tod::TimeOfDay.parse "23:00" # => 23:00:00 + Tod::TimeOfDay.parse "23+00" # => 23:00:00 + Tod::TimeOfDay.parse "23H30M58S" # => 23:30:58 Tod::TimeOfDay.parse raises an ArgumentError if the argument to parse is not parsable. Tod::TimeOfDay.try_parse will instead return nil if the argument is not diff --git a/lib/tod/time_of_day.rb b/lib/tod/time_of_day.rb index b99e554..298d088 100644 --- a/lib/tod/time_of_day.rb +++ b/lib/tod/time_of_day.rb @@ -10,10 +10,11 @@ class TimeOfDay PARSE_24H_REGEX = / \A ([01]?\d|2[0-4]) - :? + \D* ([0-5]\d)? - :? + \D* ([0-5]\d)? + \D* \z /x @@ -179,18 +180,23 @@ def self.try_parse(tod_string) tod_string = tod_string.strip tod_string = tod_string.downcase tod_string = WORDS[tod_string] || tod_string - if PARSE_24H_REGEX =~ tod_string || PARSE_12H_REGEX =~ tod_string - hour, minute, second, a_or_p = $1.to_i, $2.to_i, $3.to_i, $4 - if hour == 12 && a_or_p == "a" - hour = 0 - elsif hour < 12 && a_or_p == "p" - hour += 12 - end + tod_string.match?(/[ap]m?\z/) ? try_parse_12(tod_string) : try_parse_24(tod_string) + end - new hour, minute, second - else - nil - end + def self.try_parse_12(tod_string) + return unless PARSE_12H_REGEX =~ tod_string + + hour, minute, second, a_or_p = $1.to_i, $2.to_i, $3.to_i, $4 + hour = 0 if hour == 12 && a_or_p == "a" + hour += 12 if hour < 12 && a_or_p == "p" + new hour, minute, second + end + + def self.try_parse_24(tod_string) + return unless PARSE_24H_REGEX =~ tod_string + + hour, minute, second = $1.to_i, $2.to_i, $3.to_i + new hour, minute, second end # Determine if a string is parsable into a TimeOfDay instance diff --git a/test/tod/time_of_day_test.rb b/test/tod/time_of_day_test.rb index e618c02..ebd8224 100644 --- a/test/tod/time_of_day_test.rb +++ b/test/tod/time_of_day_test.rb @@ -63,7 +63,9 @@ def self.should_not_parse(parse_string) should_parse "13", 13, 0, 0 should_parse "1230", 12,30, 0 should_parse "08:15", 8,15, 0 + should_parse "08+15", 8,15, 0 should_parse "08:15:30", 8,15,30 + should_parse "08H15M30S", 8,15,30 should_parse "18", 18, 0, 0 should_parse "23", 23, 0, 0