开发者

How to change the date format from the default type in Rails 2.0.2 using MySQL 5.1

I am looking for a way through which I could convert my default date format to a specific user 开发者_如何学JAVAformat.

I am working on Rails 2.0.2. As we know on making use of the Scaffold command we automatically get the attributes of "id", "created_at" & "updated_at" as part of your table.

My scaffold command looks like this:-

script/server scaffold posts name:string title:string content:text

I am basically trying to implement a blog application. Now when I try to check the date when a particular blog is posted, I make use of the helper tags and through <%=h post.created_at %>in my index.html.erb file..

I am able to display the date a blog was originally created in default format which is currently like: Tue Jan 18 13:00:05 +0530 2011 via MySql 5.1 DB . I want to change this format to Month date Year.. like in the above case it would be January 18 2011.

In this regard could you please tell me how do I go about it. I am unsure of where do I need to make what changes.

Is there a way through which I can store the data in the index.html.erb and convert it then and there to the user defined format? I am not too sure of how to go about it directly from the view..

Also, I guess this, if hard coded would be a DRY(Don't Repeat Yourself) violation going against Rails principles. Could you suggest an appropriate way. Something that I can change as per a end user requirement.

Thank you..


You could use date_select_tag in the view and pass it in the time object and it would do the magic for you. Lets say for example, your time object is created at then,

<%= date_select_tag, :created_at, @user.created_at %>

Rails would take care of converting it back and forth..

Edit: Also, you can convert it into date for views using @user.created_at.to_date.strftime() as documented here - http://www.ruby-doc.org/core/classes/Time.html#M000392


The way Rails handles date and time conversion formats is independent of which database you are using. To override the default format, you should add an initializer to your application. I have mine at config/initializers/time_formats.rb. Then in that file you would define the formats you want to use throughout the app:

Time::DATE_FORMATS[:just_date] = "%b %d, %Y"
Time::DATE_FORMATS[:just_time] = "%I:%M%p"

In order to use the new formats, you will pass the symbol to a string conversion like so:

<%= @post.created_at.to_s(:just_date) %>


You can use for example ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS

You can merge in your own (in environment.rb) for example ActiveSupport::CoreExtensions::Time::Conversions::DATE_FORMATS.merge!( :default => '%m/%d/%Y', :date_time12 => "%m/%d/%Y %I:%M%p", :date_time24 => "%m/%d/%Y %H:%M" )

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜