Rails: to_date with a month/day/year format
Solution 1
You can change how a date is displayed by specifying a format like
@example.created_at.strftime("%B, %d, %Y")
# => "September, 20, 2013"
Check out various format options here
The display format is different in console and view as the default formats are different.
Solution 2
A good practice to handle displaying dates and times is to set up internationalization for your application, more info here:
http://guides.rubyonrails.org/i18n.html
An example for date (en.yml):
en:
date:
formats:
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
You can display various date formats in your views like so:
l Date.current, format: :short
The advantage of this approach is that you can easily change the way all dates are displayed in your application, since the formats are defined in one place, and your application is prepared for more locales in the future.
Solution 3
Yes..possible!
require 'date'
d = Date.parse('September, 13, 1987')
month, day, year=d.month,d.day,d.year
month # => 9
day # => 13
year # => 1987
Related videos on Youtube

Alain Goldman
I write tons of code and I drink the same amount of coffee for fuel. React / React-Native / Ruby / Rails / Meteor / Solidity / Truffle
Updated on June 18, 2022Comments
-
Alain Goldman 4 months
I have a simple question here. I have an instance variable with a created_at. How would I convert it to
Month, day, year ~ September, 13, 1987
When I tried = @example.created_at In my view it gives me
1987-09-13
Oddly enough when I do this method in console I get
Sun, 13 Sep 1987
- How do I turn my variable to month, date, year?
- Why does it return something different in console?