我是一个RoR新手。我尝试了很多东西,最后得出如下结论:
<td>
<%= Date.strptime(request.baseline_start_date, "%Y-%M-%D %H:%M:%S %Z").strftime("%M/%D/%Y")%>
</td>
但这也给了我一个错误:
$_ value need to be String (nil given)
但我知道request.baseline_start_date给了我价值(尝试单独打印它)。我不知道它说哪一个是零给的。
对如何实现格式转换有什么建议吗?
发布于 2012-10-18 05:47:47
在Rails中,您可以对字符串使用to_time
函数将其转换为Date对象:
'2012-11-14 14:27:46'.to_time.strftime('%B %e at %l:%M %p')
#=> "November 14 at 2:27 PM"
有关方便的交互式参考指南,请参阅http://www.foragoodstrftime.com/
发布于 2009-04-24 18:38:07
Date.strptime(
"2009-04-24 18:33:41 UTC",
"%Y-%m-%d %H:%M:%S %Z"
).strftime("%m/%d/%Y")
# => "04/24/2009"
我想您可能只是把格式字符串的大小写弄错了。
发布于 2012-10-18 05:50:50
请查看活动支持文档和示例,网址为:http://apidock.com/rails/ActiveSupport/CoreExtensions/DateTime/Conversions/to_formatted_s
示例
datetime = DateTime.civil(2007, 12, 4, 0, 0, 0, 0) # => Tue, 04 Dec 2007 00:00:00 +0000
datetime.to_formatted_s(:db) # => "2007-12-04 00:00:00"
datetime.to_s(:db) # => "2007-12-04 00:00:00"
datetime.to_s(:number) # => "20071204000000"
datetime.to_formatted_s(:short) # => "04 Dec 00:00"
datetime.to_formatted_s(:long) # => "December 04, 2007 00:00"
datetime.to_formatted_s(:long_ordinal) # => "December 4th, 2007 00:00"
datetime.to_formatted_s(:rfc822) # => "Tue, 04 Dec 2007 00:00:00 +0000"
或者,如果您真的想要自定义它,可以像这样定义helper:
def custom_format(time)
Time::DATE_FORMATS[:w3cdtf] = lambda { |time| time.strftime("%Y-%m-%dT%H:%M:%S# {time.formatted_offset}") }
end
https://stackoverflow.com/questions/766674
复制相似问题