在我的Rails視圖中,我有下面的代碼顯示日期時間。如何在rails中格式化datetime?
<%= link_to timeslot.opening, [@place, timeslot] %>
此行的結果如下:
2013-02-02 01:00:00 UTC
如何改變這種做法,它顯示:
2/2/13: X:00 PST
在我的Rails視圖中,我有下面的代碼顯示日期時間。如何在rails中格式化datetime?
<%= link_to timeslot.opening, [@place, timeslot] %>
此行的結果如下:
2013-02-02 01:00:00 UTC
如何改變這種做法,它顯示:
2/2/13: X:00 PST
使用Ruby的strftime()
的日期/日期時間:
<%= link_to timeslot.opening.strftime("%Y %m %d"), [@place, timeslot] %>
看一看the documentation瞭解格式化的工作原理。
謝謝!這和文檔是超級有用的。我一直無法找到如何轉換時區之間的時間。在我的例子中,時間目前是UTC,但希望它顯示PST。你知道我怎麼能做到這一點? – sharataka 2013-03-25 22:36:27
歡迎:)參考這裏:http://stackoverflow.com/questions/6118779/how-to-change-default-timezone-for-activerecord-in-rails3 – weltschmerz 2013-03-25 22:37:26
完美,感謝您的幫助! – sharataka 2013-03-25 22:46:56
對於您所要求的格式:
可以在這裏<%= 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時間,或者你想打印實際的時區,還是想要收斂? t到PST?
Try --timeslot.opening.strftime(%d /%m /%y:%H:%M:%S%Z) – Ash 2013-03-25 22:26:16
您可以使用[** stamp ** gem](https:// github .com/jeremyw /郵票)或[** strftime **](http://strfti.me/)。 – 2013-03-25 22:27:01