【问题标题】:How to show current year in view?如何在视图中显示当前年份?
【发布时间】:2011-09-04 17:36:05
【问题描述】:

有没有可以用来在视图中显示当前年份的功能?我试过了

<%= Time.now  %>

尝试显示时间,但这对我不起作用。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3


    【解决方案1】:

    【讨论】:

      【解决方案2】:

      我喜欢用:

      Time.zone.now.year
      

      这会考虑到当前时区(如果您已为特定用户覆盖它)。

      【讨论】:

        【解决方案3】:

        我宁愿使用 Date 类来获取年份而不是 Time 类(如果您只需要 Date,则无需考虑小时、分钟和秒)。

        <%= Date.today.year %>
        

        参考http://ruby-doc.org/stdlib-2.1.0/libdoc/date/rdoc/Date.html#method-c-today

        【讨论】:

          【解决方案4】:

          我认为考虑应用时区的最佳方法是:

          Date.current.year
          

          【讨论】:

          • 同意。此外,如果设置了 config.time_zoneDate.currentTime.zone.today 相同。
          • 这是最好的答案。 Date.current 是最合适的。
          【解决方案5】:

          尽管已经得到解答,但我认为对于那些想要查看所有建议解决方案的基准测试结果的人来说,它可能会派上用场。

          require 'benchmark'
          
          n = 500000
          Benchmark.bm do |x|
            x.report { n.times do ; Date.today.year; end }
            x.report { n.times do ; Date.current.year; end }
            x.report { n.times do ; Time.current.year; end }
            x.report { n.times do ; Time.zone.now.year; end }
          end
          
              user     system      total        real
          0.680000   0.030000   0.710000 (  0.709078)
          2.730000   0.010000   2.740000 (  2.735085)
          3.340000   0.010000   3.350000 (  3.363586)
          3.070000   0.000000   3.070000 (  3.082388)
          

          现在,对于这么简单的事情,它可能看起来有点过头了,但是,从一个高吞吐量应用程序的简单优化角度来看,我会考虑使用Date.today.year

          也就是说,如果您的应用程序对时区敏感,那么基于Date.currentTime.zone 的方法可能是您的最佳选择。

          看看这个精彩的Railscast by Ryan on Time Zones

          【讨论】:

            猜你喜欢
            • 2013-12-20
            • 2023-03-22
            • 2017-05-05
            • 2019-12-03
            • 2011-09-09
            • 2012-12-25
            • 1970-01-01
            • 2012-09-27
            • 1970-01-01
            相关资源
            最近更新 更多