在Rails的文本框格式的DateTime [英] Format DateTime in Text Box in Rails
问题描述
有一个简单的方法可以在Rails视图中格式化 DateTime
值的显示格式例如,如果我正在做一些事情:
<%= text_field:my_object,:start_date%>
,只想显示的日期部分:start_date
(即我想隐藏时间部分),是否有一种格式化视图中的:start_date
字符串的方式,以便它可以用于创建新的 my_object
项目并更新新的 my_object
项目?
澄清:
执行
<%= text_field
:my_object,
:start_date,
:value => @ my_object.start_date.strftime('%m /%d /%Y')%>
当对象已经存在(即项目更新)时,然而,当创建新项目时,由于start_date最初将为零,视图将抛出错误
在评估nil.strftime
,但是在那些您真正希望将文本字段日期格式化为特定方式的情况下(例如,您正在与JavaScript日期选择器集成),并且您正在处理nils,我认为只需对您现有的方法进行一些微调会做的诀窍:
:value => (@ object.start_date.blank??'':@ object.start_date.strftime('%m /%d /%Y'))
Is there an easy way to format the display of a DateTime
value in a Rails view?
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_date
string inside of the view such that it will work for creating new my_object
items and updating new my_object
items?
Just a clarification:
Doing
<%= text_field
:my_object,
:start_date,
:value => @my_object.start_date.strftime('%m/%d/%Y') %>
works beautifully when the object already exists (i.e. on item updates), however, when creating a new item, since start_date will initially be nil, the view will throw an error
while evaluating nil.strftime
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:
:value => (@object.start_date.blank? ? '' : @object.start_date.strftime('%m/%d/%Y'))
这篇关于在Rails的文本框格式的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!