【问题标题】:How do I format datetime in rails?如何在 Rails 中格式化日期时间?
【发布时间】: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

【问题讨论】:

  • 试试 - timeslot.opening.strftime(%d/%m/%y: %H:%M:%S %Z)
  • 您可以使用stamp gemstrftime

标签: ruby-on-rails datetime view


【解决方案1】:

在日期/日期时间上使用 ruby​​ 的 strftime()

<%= link_to timeslot.opening.strftime("%Y %m %d"), [@place, timeslot] %>

查看the documentation 了解格式化的工作原理。

【讨论】:

  • 谢谢!这和文档非常有用。我一直无法找到如何在时区之间转换时间。在我的示例中,时间当前是 UTC,但希望它显示 PST。你知道我该如何启用它吗?
  • 欢迎 :) 参考这个:stackoverflow.com/questions/6118779/…
【解决方案2】:

对于您要求的格式:

<%= 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

【讨论】:

    【解决方案3】:

    您应该为此使用助手。

    如果您想从 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] %>
    

    【讨论】:

      【解决方案4】:

      要获得您在示例中寻找的精确日期格式,请使用以下 strftime 格式字符串"%-d/%-m/%y: %k:00 PST"

      但是,这可能不是您想要的。请在您的问题中说明 (a) 您想对时间字段做什么(例如,您是否总是想在整点显示时间?X:00)和(b) 您是一直想报告 PST 时间还是想打印实际时区,还是想转换为 PST??

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-20
        • 1970-01-01
        • 2019-01-05
        • 2021-09-24
        • 2017-03-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多