44361

Change format for date input in Rails 3?

Question:

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 <em>displaying</em> 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?

Answer1:

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 <em>format</em> 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.

Answer2:

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

Recommend

  • Image manipulation with javascript
  • Use WPF Controls in Web project
  • Date Formatting in php for string with AM and PM
  • Duplicate javascript for Codrops MULTI-LEVEL PUSH MENU
  • Accessing Flurry User ID
  • How can i find the length of this Json object
  • Can the Microsoft TextTransform utility be used standalone?
  • How do I convert an SQL date result to British format (dd/mm/yyyy)
  • Console.log double logging from web workers
  • How can I find a style trigger-embedded element by name in WPF?
  • Numpy 3d array indexing
  • Adding new user Tab in the Doxygen Layout
  • py.test passing results of one test to another
  • What cross-browser technology do you use in your web applications to manipulate on client machines?
  • Get exact date by providing week number of month and day?
  • Ordering of eigenvectors when calculating eigenvectors using LAPACK's ssteqr
  • PHP Carbon “month()” method generates wrong DateTime
  • ValidationResult Returned From IValidatableObject.Validate Is Not Localized
  • iOS Validation failed -> Bundle is invalid (Xcode 6.2, iOS 8.2)
  • get helsinki local time regardless of local time zone
  • Ignore “The” when sorting a View in Drupal
  • jQuery - how to validate a date of birth using jQuery Validation plugin?
  • Can I disable IE compatibility mode only for content within a ?
  • How would I send and receive packets over a WebSocket in Javascript
  • Implementing HMAC-SHA256 for Keybase in Javascript
  • Reflection / C# typing errors when publishing an F# class implementing an interface
  • custom string delimiters stringtemplate-4
  • Insertion large number of Entities into SQL Server 2012 [duplicate]
  • Efficient & Pythonic way of finding all possible sublists of a list in given range and the minim
  • Recording values of radio buttons in ember
  • jwtBearer bearer token with rc-1 update to ASP.Net 5
  • Jackson Parser: ignore deserializing for type mismatch
  • Validaiting emails with Net.Mail MailAddress
  • Shallow update not allowed (git > 1.9)
  • How can I use Kendo UI with Razor?
  • jquery mobile loadPage not working
  • How to format a variable of double type
  • Matrix multiplication with MKL
  • How to include full .NET prerequisite for Wix Burn installer
  • Qt: Run a script BEFORE make