I had a really hard time finding information on how to convert a string in your own custom format into a Time object in Ruby. Turns out it's pretty easy but poorly documented. Use the method DateTime.strptime. Documentation on that is hard to come by, but you pass in the string containing the time as the first parameter, then the second parameter is the format string. This returns a DateTime object, call .to_time on it to get a Time object. Example:
DateTime.strptime("2009/04/16 19:52:30", "%Y/%m/%d %H:%M:%S").to_time
The format uses the same syntax as what you pass in to strftime to print out a date. The page
http://snippets.dzone.com/posts/show/2255 has a complete listing of all format types.
3 comments:
Beautiful! I'm using it in my app right now. Thanks.
thanks! excatly what i was looking for
Exactly what I was looking for!
Post a Comment