0

I need a date of birth as a plain text in Ruby on Rails application. So here is the main part of a code I'm using to do it

   if @date_of_birth_as_text.present? and Date.parse(@date_of_birth_as_text).nil?
      errors.add :date_of_birth_as_text, "cannot be parsed"
    end

So it makes everything to a date. Look at it, it's quite odd

1.9.3p194 :002 > Date.parse("12 12 addd")
 => Sun, 12 Aug 2012 
1.9.3p194 :003 > Date.parse("12 12 october")
 => Fri, 12 Oct 2012 
1.9.3p194 :004 > Date.parse("12 13 october")
 => Sat, 13 Oct 2012 
1.9.3p194 :005 > Date.parse("13 13 october")
 => Sat, 13 Oct 2012 
1.9.3p194 :006 > Date.parse("13 13 2012")
 => Mon, 13 Aug 2012 
1.9.3p194 :007 > Date.parse("13 01 2012")
 => Mon, 13 Aug 2012 
1.9.3p194 :008 > Date.parse("10 01 2012")
 => Fri, 10 Aug 2012 
1.9.3p194 :009 > Date.parse("10 01 2010")
 => Fri, 10 Aug 2012 

I want to change it a little bit. I want a date in format either"MM (any delimeter or not) dd (any delimeter or not) YYYY" or "dd (any delimeter) MM (any delimeter) YYYY" can be parsed. Or something like that, but not "12 12 addd".

How can I reach it?

P.S I saw gem chronic, please don't suggest me to it.

1 Answers1

0

Try using Date.strptime:

1.9.3-p194 :017 > Date.strptime( '08-29-2012', '%m-%d-%Y' )
 => #<Date: 2012-08-29 ((2456169j,0s,0n),+0s,2299161j)> 

Documentation: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/date/rdoc/Date.html#method-c-strptime

David
  • 751
  • 3
  • 13