Ruby-on-rails 如何在 rails 中格式化日期时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15625947/
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
How do I format datetime in rails?
提问by sharataka
In my Rails view, I have the below code that displays a datetime.
在我的 Rails 视图中,我有以下显示日期时间的代码。
<%= link_to timeslot.opening, [@place, timeslot] %>
The result of this line is below:
这一行的结果如下:
2013-02-02 01:00:00 UTC
How do I change this so it displays as:
如何更改它以使其显示为:
2/2/13: X:00 PST
回答by dchacke
Use ruby's strftime()on dates/datetimes:
strftime()在日期/日期时间使用 ruby :
<%= link_to timeslot.opening.strftime("%Y %m %d"), [@place, timeslot] %>
Have a look at the documentationto find out how the formatting works.
查看文档以了解格式的工作原理。
回答by Luís Ramalho
You should use a helper for this.
您应该为此使用助手。
If you want to convert from UTC to PST you can use the in_time_zonemethod
如果要从 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] %>
回答by Ashley
For the format you have requested:
对于您要求的格式:
<%= link_to timeslot.opening.strftime(%d/%m/%y: %H:%M:%S %Z), [@place, timeslot] %>
More options available here:
此处提供更多选项:
http://rorguide.blogspot.co.uk/2011/02/date-time-formats-in-ruby-on-rails.html
http://rorguide.blogspot.co.uk/2011/02/date-time-formats-in-ruby-on-rails.html
回答by stevejpurves
to get the precise date formatting that you are looking for in your example use the following strftime format string "%-d/%-m/%y: %k:00 PST"
要获得您在示例中查找的精确日期格式,请使用以下 strftime 格式字符串 "%-d/%-m/%y: %k:00 PST"
However, that may not be exactly what you want.Please clarify in your question (a) what you want to do with the time field (e.g. are you always wanting to display a time on the hour? X:00) and (b) are you always wanting to report PST times or do you want to print the actual timezone, or do you want to convert to PST??
但是,这可能不是您想要的。请在您的问题 (a) 中澄清您想对时间字段做什么(例如,您是否总是想在整点显示时间?X:00)和 (b)您是一直想报告 PST 时间还是想打印实际时区,还是想转换为 PST?

