0

I am using a text_field for date input in Rails 3 and would like the date to be formatted as mm/dd/yyyy.

While I've found a few solutions for displaying the date in that way, I haven't run across a workable method for accepting that format as an input.

The problem is that in the case of ambiguous dates like "09/05/2011", Rails interprets it as "May 9th" rather than "September 5th."

What is the best way to get Rails 3 to interpret those sorts of inputs according to the mm/dd/yyyy format?

2 Answers 2

3

Hopefully your target audience is solely American, since that date format is not used many places outside the US.

Anyway, you just want to validate the format of the string:

validates_format_of :the_date, :with => /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/

That's a very rudimentary pattern that validates the format of the string, but not the actual values between the separators. If you want to do that, your best bet is probably just to try parsing the date with Date#strptime and see if it parses or not.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. Unfortunately, I may not have been clear in what I'm looking for. I've edited my question to clarify that the problem is about the way Rails interprets ambiguous dates.
+1 for the answer. The problem isn't how Rails interprets ambiguous dates, it's that ambiguous dates exist. Rails has no good way of unequivocally determining the location of the user, which would be a hint to the format of the date. You, as the developer, need to help it, either by asking the user what their preferred date format is, or by specifying a unique format that sidesteps the problem. Human interface people would suggest you need to avoid a text box and use a calendar pop-up or interface that avoids the problem entirely.
1

I ran into an issue where users were filling out a text field with month/day/year. But due to the new Date parsing, Rails admitted they entered day/month/year. I solved it by patching Date._parse in Rails. Therefore I added a date_patch.rb in the initializers folder.

require 'time'

class Date
  class << self
    alias :org_parse :_parse

    # switch the month and day field for expecting US dates
    def _parse(str, comp=true)
      str = str.sub(/(\d{1,2})\/(\d{1,2})\/(\d{1,4})/, '\2/\1/\3')
      org_parse str, comp
    end
  end
end

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.