Changing Time format globally

By default, whenever you stick a Time in a web page, e.g. <%=
created_at %>, it gets formatted as an unwieldy string: “Thu May 24
21:19:11 BST 2007”

I’ve discovered that I can improve this using <%= created_at.to_s(:db)
%> to get “2007-05-24 21:19:11”

However, is there a way to set the default conversion globally? Or do
I have to find every template which includes a Time field and manually
change it?

Thanks,

Brian.

candlerb wrote:

By default, whenever you stick a Time in a web page, e.g. <%=
created_at %>, it gets formatted as an unwieldy string: “Thu May 24
21:19:11 BST 2007”

I’ve discovered that I can improve this using <%= created_at.to_s(:db)
%> to get “2007-05-24 21:19:11”

However, is there a way to set the default conversion globally? Or do
I have to find every template which includes a Time field and manually
change it?

http://www.ruby-forum.com/topic/57923


Cheers,

  • Jacob A.

Create a helper that parses the date and returns your desired format.
Look
up the documentation on helpers.

Create a helper that parses the date and returns your desired format.

That would mean I still had to modify every instance of a time
variable in every template: e.g. changing them to
<%= time_fmt(created_at) %>

But Jacob’s pointer for setting the :default time display looks to be
what I want. Thank you!

You could do this:
Time::DATE_FORMATS[:clean_with_time] = “%B %d, %Y at %I:%M %p”

inside either your environment.rb file(non rails edge) or inside a new
file in the config/initializers directory (e.g. config/initializer/
time.rb).

Then you can use that by doing:

created_at.to_s(:clean_with_time)

Robert

This screencast is all about it: http://railscasts.com/episodes/31

Zach I.
→ Blog – http://www.zachinglis.com
→ Company – http://www.lt3media.com
→ Portfolio – http://portfolio.zachinglis.com

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs