Topic: Date Format

Is there anyway I can format my dates with the suffix's of st, rd and th?

Re: Date Format

you can do this:

time = Time.now # some time/date object
time.strftime("%b #{time.day.ordinalize} %I:%M %p")

Railscasts - Free Ruby on Rails Screencasts

Re: Date Format

Cheers

One thing I noticed that I had declared it in the def index, so it then becomes unavailable to all other pages.

Is there anyway I can declare it once and use it throughout the app.

def index
    @products = Product.find_products_for_sale
    @current_time = Time.now # some time/date object
    Time.strftime("%b #{Time.day.ordinalize} %I:%M %p")
  end

Infact just noticed that the code isn't working.

Re: Date Format

The code isn't working for two reasons.

1. You need to call "strftime" and "day" on the @current_time object.
2. The strftime method outputs a string, but you aren't displaying that here. You would want to do that in the view. For example:

# in some view:
<%= @current_time.strftime("%b #{@current_time.day.ordinalize} %I:%M %p") %>

If you want to make this accessible from all views the best way is probably a helper method. Get it working first then I can show you how to do that.

Railscasts - Free Ruby on Rails Screencasts

Re: Date Format

So

def index
    @products = Product.find_products_for_sale
    Time.now
    @current_time = Time.strftime("%b #{time.day.ordinalize} %I:%M %p")
  end

Re: Date Format

Not quite:

def index
  @products = Product.find_products_for_sale
  @current_time = Time.now.strftime("%b #{Time.now.day.ordinalize} %I:%M %p")
end

That should contain a string so you can print it in the view.

Railscasts - Free Ruby on Rails Screencasts

Re: Date Format

ok, that makes sense.

How would I turn that into a helper then?

Re: Date Format

You can do this:

# in application_helper.rb
def ordinalized_time(time = Time.now)
  time.strftime("%b #{time.day.ordinalize} %I:%M %p")
end

You can then call this from any view:

<%= ordinalized_time %>

or pass a time:

<%= ordinalized_time(Time.now.end_of_month) %>

Railscasts - Free Ruby on Rails Screencasts

Re: Date Format

Excellent, I think I'm getting the hang of this by the minute.  So when you say pass a time, that means I can override what was in the helper.

Re: Date Format

Yes, you can override the time used in the helper method by passing a time as a parameter.

Railscasts - Free Ruby on Rails Screencasts

Re: Date Format

Cool, thanks for your help today. I'm just on Chapter 9 now, with Ajax, should be fun.