Search code examples
rubydatestrptime

Converting string to date with Ruby


I have date as string in such format: 23 Nov. 2014. Sure, it's easy to convert this string into date with such expression:

Date.strptime(my_string, '%d %b. %Y')

But there is one issue when month is May - there is no dot, like 23 May 2014. And my expression breaks.

Could somebody help with this issue? How can I make universal expression for my cases?


Solution

  • Remove the period from my_string and from the date pattern.

    Date.strptime(my_string.sub('.', ''), '%d %b %Y')
    

    That's assuming you have at most one dot in my_string. If there may be several, use gsub.

    Date.strptime(my_string.gsub('.', ''), '%d %b %Y')