Consistent Date Formatting in Ruby on Rails 5+
If you’ve ever dealt with dates in Rails, particularly accepting dates from user input and then displaying them, you’re familiar with two clunky experiences:
- The awful default month, day, year, hour, minute, second dropdowns
- The complete mess of a date that you get when you force that field to be represented as a text input in a form.
In a hurry? Scroll on down to the bottom for the copy-paste-ready code snippet to make everything better like magic.
Part 1: Getting Date
to format itself as desired
There are a bunch of core extensions to Date in ActiveSupport, but none of them create a new date class. If you’re working with Date
, which is what Rails returns when you have a date
column in your database, the method converting that date into a string is Dateto_formatted_s
. The ActiveSupport
extensions add this method, and they alias the to_s
method to it, so when you call Dateto_s
...