user2360274
user2360274

Reputation:

Change rails time formatting

I have some times that I am showing in my view

<td><%= something.foo_time %></td>
<td><%= something.bar_time %></td>

Right now they display as

2000-01-01 05:24:00 UTC
2000-01-01 15:24:00 UTC

But since I am not collecting the date, I want to just show the time, but in AM/PM style without the year and time zone.

I have tried using the strf formating http://www.ruby-doc.org/core-2.0/Time.html#method-i-strftime but it does not work

<td><%= something.foo_time("%I:%M%p") %></td>

I also tried

<td><%= something.foo_time "%H:%M:" %></td>

And It did not work either.

How can I go from

2000-01-01 15:24:00 UTC

To

3:24 PM

Upvotes: 0

Views: 121

Answers (2)

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

The simplest approach would be to do this:

something.foo_time.strftime("%I:%M%p")

However, I'd look into Rails' DATE_FORMATS at the following URL and either use a default if it exists, or create your own by adding it via an initializer.

http://api.rubyonrails.org/classes/Time.html

Then you can do this:

something.foo_time.to_s(:time)

Upvotes: 1

Luiz E.
Luiz E.

Reputation: 7229

you can always create a helper

module ApplicationHelper
   def display_date(input_date)
    if !input_date
      return ''
    end

    return input_date.strftime("%d/%m/%Y")
  end

end

and then call in your view like <%= display_date time_var %>
my example doesn't format the date to AM/PM style, but you can easily find how to do this on the documentation, like the link you've posted: t.strftime("at %I:%M%p") #=> "at 08:37AM"

my method could be changed to return input_date.strftime("%I:%M%p") according to the link

Upvotes: 1

Related Questions