【发布时间】:2013-03-15 14:12:18
【问题描述】:
在我的 Rails 视图中,我有以下显示日期时间的代码。
<%= link_to timeslot.opening, [@place, timeslot] %>
这一行的结果如下:
2013-02-02 01:00:00 UTC
如何更改它以使其显示为:
2/2/13: X:00 PST
【问题讨论】:
标签: ruby-on-rails datetime view
在我的 Rails 视图中,我有以下显示日期时间的代码。
<%= link_to timeslot.opening, [@place, timeslot] %>
这一行的结果如下:
2013-02-02 01:00:00 UTC
如何更改它以使其显示为:
2/2/13: X:00 PST
【问题讨论】:
标签: ruby-on-rails datetime view
在日期/日期时间上使用 ruby 的 strftime():
<%= link_to timeslot.opening.strftime("%Y %m %d"), [@place, timeslot] %>
查看the documentation 了解格式化的工作原理。
【讨论】:
对于您要求的格式:
<%= link_to timeslot.opening.strftime(%d/%m/%y: %H:%M:%S %Z), [@place, timeslot] %>
此处提供更多选项:
http://rorguide.blogspot.co.uk/2011/02/date-time-formats-in-ruby-on-rails.html
【讨论】:
您应该为此使用助手。
如果您想从 UTC 转换为 PST,您可以使用 in_time_zone 方法
def convert_time(datetime)
time = Time.parse(datetime).in_time_zone("Pacific Time (US & Canada)")
time.strftime("%-d/%-m/%y: %H:%M %Z")
end
<%= link_to convert_time(timeslot.opening), [@place, timeslot] %>
【讨论】:
要获得您在示例中寻找的精确日期格式,请使用以下 strftime 格式字符串"%-d/%-m/%y: %k:00 PST"
但是,这可能不是您想要的。请在您的问题中说明 (a) 您想对时间字段做什么(例如,您是否总是想在整点显示时间?X:00)和(b) 您是一直想报告 PST 时间还是想打印实际时区,还是想转换为 PST??
【讨论】: