Skip to content

Instantly share code, notes, and snippets.

@ashirazi
Created January 1, 2013 00:33
Show Gist options
  • Save ashirazi/4424177 to your computer and use it in GitHub Desktop.
Save ashirazi/4424177 to your computer and use it in GitHub Desktop.
String#strptime Ruby needs symmetry for Time#strftime. If a Time can be converted to a string (given a pattern), then a String should be convertible to a Time.
# This really should belong in String, not Date...
class String
# Calculate the Time represented by this string, and the (optional) time pattern
# that describes this string (see Time#strftime).
# Returns a nil time if the String does not match the pattern, or the pattern is invalid.
def strptime(format=nil)
date = format ? Date.strptime(self, format) : Date.strptime(self)
date.to_time
rescue
nil
end
end
@rwilcox
Copy link

rwilcox commented Jan 16, 2014

Thanks, Arild. I wanted this a while back. 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment