【问题标题】:Is there a time ahead words in rails (opposite of time_ago_in_words)Rails 中是否有提前的单词(与 time_ago_in_words 相对)
【发布时间】:2015-09-24 01:17:52
【问题描述】:

是否有与 time_ago_in_words 相反的 rails helper ?我似乎找不到相反的东西......从现在起我可以有 7 天的时间转换为“大约 1 周内”。

我可以让它为过去工作:

 <%= time_ago_in_words( milestone.due_date) %>

但这对未来不起作用:

   <%= time_ahead_in_words(milestone.due_date) %>

难住了。

【问题讨论】:

    标签: ruby-on-rails helpers


    【解决方案1】:

    distance_of_time_in_words 是您所追求的。请注意:

    1. distance_of_time_in_words 不是假设你的意思是从现在开始,所以你必须用@987654326 告诉它@。例如
    appointment_start_time = ActiveSupport::TimeZone['Sydney'].parse("2022-11-14 07:00:00 UTC")
    distance_of_time_in_words(Time.current, appointment_start_time)
    => "about 2 years"
    
    1. 如果时间已经过去,distance_of_time_in_words 仍然会返回结果,所以要小心!

    2. 如果在 Rails 控制台中使用 distance_of_time_in_wordsyou need to prepend helper.,像这样:

    helper.distance_of_time_in_words(Time.current, appointment_start_time)
    => "about 2 years"
    

    参考资料:

    【讨论】:

      【解决方案2】:

      听起来您需要“distance_in_time”辅助方法。

      例如

          from_time = Time.current
      helper.distance_of_time_in_words(from_time, from_time + 50.minutes)
      
      =>about 1 hour
      

      更具体地说,在您的情况下,您会这样做:

      from_time = Time.current
          helper.distance_of_time_in_words(from_time, from_time + 6.days)
      
          =>about 7 days
      

      【讨论】:

        【解决方案3】:

        您可以使用distance_of_time_in_words。例如:

        distance_of_time_in_words(Time.current, milestone.due_date)
        

        将等同于您的 time_ahead_in_words 伪代码。

        详情请见distance_of_time_in_words documentation

        【讨论】:

          【解决方案4】:

          您可以改用distance_of_time_in_words(from_time, to_time = 0, options = {})

          所以你可以这样设置:

          &lt;%= distance_of_time_in_words(Time.now, milestone.due_date) %&gt;

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-09-17
            • 2018-05-05
            • 1970-01-01
            • 2021-05-16
            • 1970-01-01
            • 1970-01-01
            • 2010-10-11
            • 2019-12-25
            相关资源
            最近更新 更多