Rails: to_date with a month/day/year format

10,145

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
Share:
10,145

Related videos on Youtube

Alain Goldman
Author by

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, 2022

Comments

  • Alain Goldman
    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

    1. How do I turn my variable to month, date, year?
    2. Why does it return something different in console?

Related