Converting string to date with Ruby

1.1k views Asked by At

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?

3

There are 3 answers

2
Michael Laszlo On BEST ANSWER

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')
4
daremkd On

I think you're using the wrong method. Date#parse should work with almost "anything" (see TinMan answer and comment for clarification of when not to use parse) and provide the same object:

p Date.parse('23 Nov 2014') #=> #<Date: 2014-11-23 ((2456985j,0s,0n),+0s,2299161j)>
p Date.parse('23 Nov. 2014') #=> #<Date: 2014-11-23 ((2456985j,0s,0n),+0s,2299161j)> same object as with the previous line
2
the Tin Man On

The parse method attempts to find matching date or date-time formats, then parse the string to return the values used to create a new Date or DateTime. There are many different formats it supports, which is convenient, however the process of scanning to find a match slows the parsing time.

Also, some formats in common use don't necessary "fit". Consider what's happening here:

Date.parse '31/01/2001'
=> #<Date: 2001-01-31 ((2451941j,0s,0n),+0s,2299161j)>

The date string in '%d/%m/%Y' (day, month, year) format is parsed, though it's not common in the U.S., because Ruby isn't a US-centric language. Reversing the first two fields results in:

Date.parse '01/31/2001'
ArgumentError: invalid date
  from (irb):4:in `parse'
  from (irb):4
  from /Users/greg/.rbenv/versions/2.1.5/bin/irb:11:in `<main>'
irb(main):005:0> Date.parse '31/01/2001'