Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a Date as words in Rails

So I have a model instance that has a datetime attribute. I am displaying it in my view using:

<%= @instance.date.to_date %> 

but it shows up as: 2011-09-09

I want it to show up as: September 9th, 2011

How do I do this?

Thanks!

like image 975
goddamnyouryan Avatar asked Aug 06 '11 22:08

goddamnyouryan


5 Answers

<%= @instance.date.strftime("%B %d, %Y") %>

This would give you "September 9, 2011".

If you really needed the ordinal on the day ("th", "rd", etc.), you could do:

<%= @instance.date.strftime("%B #{@instance.date.day.ordinalize}, %Y") %>
like image 50
Dylan Markow Avatar answered Oct 01 '22 09:10

Dylan Markow


There is an easier built-in method to achieve the date styling you are looking for.

<%= @instance.datetime.to_date.to_formatted_s :long_ordinal %>

The to_formatted_s method accepts a variety of format attribute options by default. For eaxmple, from the Rails API:

date.to_formatted_s(:db)            # => "2007-11-10"
date.to_s(:db)                      # => "2007-11-10"

date.to_formatted_s(:short)         # => "10 Nov"
date.to_formatted_s(:long)          # => "November 10, 2007"
date.to_formatted_s(:long_ordinal)  # => "November 10th, 2007"
date.to_formatted_s(:rfc822)        # => "10 Nov 2007"

You can see a full explanation here.

like image 22
Charles Worthington Avatar answered Oct 01 '22 09:10

Charles Worthington


The Rails way of doing this would be to use

<%=l @instance.date %>

The "l" is short for "localize" and converts the date into a readable format using the format you defined in your en.yml. You can define various formats in the yml file:

en:
  date:
    formats:
      default: ! '%d.%m.%Y'
      long: ! '%a, %e. %B %Y'
      short: ! '%e. %b'

To use another format than the default one in your view, use:

<%=l @instance.date, format: :short %>
like image 29
morgler Avatar answered Oct 01 '22 09:10

morgler


Rails has it built into ActiveSupport as an inflector:

ActiveSupport::Inflector.ordinalize(@instance.date.day)
like image 20
JP Silvashy Avatar answered Oct 01 '22 09:10

JP Silvashy


You also have <%= time_tag time %> in rails

like image 23
Alex Chin Avatar answered Oct 01 '22 11:10

Alex Chin