【问题标题】:Ruby and Rails "Date.today" formatRuby 和 Rails 的“Date.today”格式
【发布时间】:2015-09-26 18:43:58
【问题描述】:

在 IRB 中,如果我运行以下命令:

require 'date'
Date.today

我得到以下输出:

=> #<Date: 2015-09-26 ((2457292j,0s,0n),+0s,2299161j)> 

但在 Rails 控制台中,如果我运行 Date.today,我会得到:

=> Sat, 26 Sep 2015 

我查看了 Rails 的 Date class,但找不到 Rails 的 Date.today 显示输出的方式与 Ruby 的输出不同。

谁能告诉,在 Rails 中,Date.todayDate.tomorrow 如何格式化日期以很好地显示?

【问题讨论】:

    标签: ruby-on-rails ruby date activesupport


    【解决方案1】:

    您的问题的答案是ActiveSupport's core extension to Date class。它覆盖了inspectto_s 的默认实现:

    # Overrides the default inspect method with a human readable one, e.g., "Mon, 21 Feb 2005"
    def readable_inspect
      strftime('%a, %d %b %Y')
    end
    alias_method :default_inspect, :inspect
    alias_method :inspect, :readable_inspect
    

    命令行示例:

    ruby-2.2.0 › irb
    >> require 'date'
    => true
    >> Date.today
    => #<Date: 2015-09-27 ((2457293j,0s,0n),+0s,2299161j)>
    >> require 'active_support/core_ext/date'
    => true
    >> Date.today
    => Sun, 27 Sep 2015
    

    【讨论】:

    • 谢谢 Alexey,这正是我想要的!
    【解决方案2】:

    Rails 的 strftimeto_s 方法应该可以满足您的需求。

    例如,使用to_s:

    2.2.1 :004 > Date.today.to_s(:long)
     => "September 26, 2015" 
    2.2.1 :005 > Date.today.to_s(:short)
     => "26 Sep" 
    

    【讨论】:

    • 嗨 Brito,我的问题是当我运行 Date.today 时,rails 是如何显示的 => 2015 年 9 月 26 日星期六?
    • @Lalu 可能是因为 Rails 在初始化 Date 时在某处调用了to_s。不过,我必须进行更多研究才能确认。
    • 是的 Brito,我也是这么想的,但我想不通。如果您发现,请更新您的答案。还是谢谢!
    【解决方案3】:

    如果你运行这个:

    require 'date'
    p Date.today.strftime("%a, %e %b %Y")
    

    你会得到这个:“2015 年 9 月 26 日,星期六”

    【讨论】:

      猜你喜欢
      • 2011-01-10
      • 1970-01-01
      • 1970-01-01
      • 2011-03-19
      • 2012-11-07
      • 1970-01-01
      • 2011-01-04
      • 2012-08-09
      • 1970-01-01
      相关资源
      最近更新 更多