Ruby-on-rails 在 Rails 的文本框中格式化日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1422274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:45:28  来源:igfitidea点击:

Format DateTime in Text Box in Rails

ruby-on-railsdatetime

提问by jerhinesmith

Is there an easy way to format the display of a DateTimevalue in a Rails view?

有没有一种简单的方法来格式化DateTimeRails 视图中值的显示?

For example, if I'm doing something like:

例如,如果我正在做类似的事情:

<%= text_field :my_object, :start_date %>

and only want to display the Date part of the :start_date(i.e. I want to hide the time part), is there a way to format the :start_datestring inside of the view such that it will work for creating new my_objectitems and updating new my_objectitems?

并且只想显示日期部分:start_date(即我想隐藏时间部分),有没有办法格式化:start_date视图内的字符串,以便它可以用于创建新my_object项目和更新新my_object项目?

Just a clarification:

只是澄清一下:

Doing

正在做

<%= text_field 
       :my_object,
       :start_date,
       :value => @my_object.start_date.strftime('%m/%d/%Y') %>

works beautifullywhen the object already exists (i.e. on item updates), however, when creating a newitem, since start_date will initially be nil, the view will throw an error

当对象已经存在时(即项目更新时)效果很好,但是,当创建项目时,由于 start_date 最初为 nil,视图将​​抛出错误

while evaluating nil.strftime

回答by Dave Rapin

Some great suggestions here, however in those cases where you really do want your text field date formatted a specific way (say you're integrating with a javascript date picker), and you're dealing with nils, I think simply making a minor tweak to your existing method would do the trick:

这里有一些很好的建议,但是在那些您确实希望以特定方式格式化文本字段日期的情况下(假设您正在与 javascript 日期选择器集成),并且您正在处理 nils,我认为只需进行小幅调整到您现有的方法可以解决问题:

:value => (@object.start_date.blank? ? '' : @object.start_date.strftime('%m/%d/%Y'))

回答by Alessandra Pereyra

I can think of three ways:

我可以想到三种方式:

1) Creating a new method on the model that would format your date however you need it to be

1)在模型上创建一个新方法来格式化你的日期,但是你需要它

2) Creating a helper method that would do the same

2)创建一个可以做同样事情的辅助方法

3) Have you tried doing:

3)您是否尝试过:

<%= text_field 
   :my_object,
   :start_date,
   :value => @my_object.try(:start_date).try(:strftime,'%m/%d/%Y') %>

回答by Eimantas

If your form is tied to an object, (something like <% form_for(:object) do |f| %>) you should use <%= f.text_field :start_date, :value => f.object.start_date.to_s(:date_format) %>

如果您的表单绑定到一个对象,(类似<% form_for(:object) do |f| %>),您应该使用<%= f.text_field :start_date, :value => f.object.start_date.to_s(:date_format) %>

then you can register your :date_formatin config/environment.rb

然后你可以:date_format在 config/environment.rb 中注册你的

Not sure why you want to do this, but i hope it's for presentation purposes only.

不知道您为什么要这样做,但我希望它仅用于演示目的。

回答by Thomas Schmidt

In my application_helper.rb I put

在我的 application_helper.rb 我把

def nice_date_form(the_date)
   return the_date.strftime('%d-%m-%Y')
end

In any edit.html.erb view file with a jQuery datepicker I then use:

在任何带有 jQ​​uery datepicker 的 edit.html.erb 视图文件中,我然后使用:

<% if @activity.end_date? %> 
    <%= f.text_field :end_date, :value => nice_date_form(@activity.end_date) %>
<% else %>
    <%= f.text_field :end_date %>
<% end %>

回答by pdobb

This can be handled DRYly at the model layer using the Rails-provided <attribute>_before_type_castmethod variant. Rails already uses this method for doing just this type of formatting, so we're just overwriting the default. For example:

这可以使用 Rails 提供的<attribute>_before_type_cast方法变体在模型层进行 DRY 处理。Rails 已经使用这种方法来进行这种类型的格式化,所以我们只是覆盖了默认值。例如:

class MyModel
   def start_date_before_type_cast
      return unless self[:start_date]
      self[:start_date].strftime('%m/%d/%Y')
   end
end

This way, anywhere you have a text field for the MyModel#start_date field you get formatting for "free".

这样,在任何有 MyModel#start_date 字段的文本字段的地方,您都可以“免费”格式化。

回答by montrealmike

In a helper

在帮手

def l(value, options = {})
   return nil unless value.present?
   value = value.to_date if value.is_a? String
   super(value, options)
end

Then in the view

然后在视图中

<%= f.text_field :end_date, class: "datepicker" :value => l(@activity.end_date) %>

Here lis a rails helper (I18n.l) which can be locale specificand can take a format. Examples:

l是一个 rails helper ( I18n.l),它可以是特定语言环境的并且可以采用一种格式。例子:

l(@activity.end_date, format: :short)
l(@activity.end_date, format: "%d-%m-%Y")

回答by ax.

if you don't want to enter the date in a textfield, but in a less error prone select field, you could use the ActionView::Helpers::DateHelper, select_date(). see Accessing date() variables send from the date helper in railshere on SO on how to process the return values.

如果您不想在文本字段中输入日期,但在不太容易出错的选择字段中,您可以使用ActionView::Helpers::DateHelperselect_date()。关于如何处理返回值,请参阅访问从 rails 中的日期助手发送的 date() 变量