【问题标题】:Rails: DateTime helper for today, tomorrowRails:今天,明天的日期时间助手
【发布时间】:2015-06-02 08:33:04
【问题描述】:

Rails(或 gem)中是否有一个 DateTime 助手,它检查给定的 DateTime 是否是今天、明天......并产生像 today, at 3pmtomorrow, at 3pmnext Tuesday, at 3pm 这样的输出?

我找到了 time_ago_in_words 助手 http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html#method-i-time_ago_in_words 但这是一个不同的用例。

我找不到像上面的例子那样格式化DateTime 对象的任何东西。我找到了 JavaScript (http://momentjs.com/docs/#/displaying/calendar-time/) 的解决方案,我正在 Ruby 中寻找类似的解决方案。

【问题讨论】:

    标签: ruby-on-rails ruby datetime


    【解决方案1】:

    您可以通过这种方式将DateTime 转换为Timeyour_date_time.to_time,然后使用time_ago_in_words

    如果您想要一种非常具体的显示日期的方式,您应该创建自己的助手。否则,您可以尝试将 time_ago_in_words 与自定义助手组合。

    PS:您也可以像这样编辑time_ago_in_words 语言环境

    "en":
      datetime:
        distance_in_words:
          about_x_hours:
            # The defaults are "about 1 hour" and "about %{count} hours"
            one: "1 hour"
            other: "%{count} hours"
    

    完整参考:https://github.com/rails/rails/blob/master/actionview/lib/action_view/locale/en.yml#L18

    【讨论】:

      【解决方案2】:

      你可以使用你找到的gem,只需先将DateTime转换为Time

      datetime = DateTime.now
      time = datetime.to_time
      #use time ago gem
      

      【讨论】:

        【解决方案3】:

        您可以将今天的日期时间检查为

        DateTime.now.today? // returns boolean value if DateTime value is today's date
        

        明天你可以检查如下:

        DateTime.tomorrow //will return tomorrow's date.
        

        【讨论】:

          【解决方案4】:

          我不太确定我是否完全理解您的要求,但如果您想将时间定在今天下午 3 点,您可以编写以下内容

          DateTime.now.at_midday + 3.hours
          

          上述代码的优点在于它将时间设置为一个固定点,并允许您从中计算相对时间。

          这里有更多来自API docs的信息

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-07-28
            • 1970-01-01
            • 2017-09-18
            • 2020-05-12
            • 1970-01-01
            相关资源
            最近更新 更多