【问题标题】:Rails 3 - Is there a helper that given a date will return "Today", "Yesterday", or "x days ago"?Rails 3 - 有没有给定日期的助手会返回“今天”、“昨天”或“x 天前”?
【发布时间】:2012-10-02 15:16:37
【问题描述】:

基本上,我想要“time_ago_in_words”的等价物,但以天为单位,仅此而已。 (对于“日期”,而不是“日期时间”)

这样的东西存在吗?

谢谢!
丹尼尔

【问题讨论】:

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


    【解决方案1】:

    您可以非常直接地为自己制作这个助手。

    使用日期计算的天数只是delta = (to_date - from_date).to_i

    today = Date.today
    past_date = Date.new(2012, 9, 28)
    puts (today - past_date).to_i
    

    这是一个完整的示例,包括实际的消息构造:

    def days_ago_in_words(from_date, to_date, options={})
      delta = (to_date - from_date).to_i
      I18n.with_options :locale => options[:locale], :scope => :'datetime.distance_in_words' do |locale|
        locale.t :x_days, :count => delta
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-27
      相关资源
      最近更新 更多