简体   繁体   English

日期操作Rails 4.1

[英]Date manipulation Rails 4.1

I have created an Events Model with the event date. 我用事件日期创建了一个事件模型。

So when I display it I want it to show : 所以当我显示它时,我希望它显示:

  1. "Tomorrow" ( If the event date is tomorrow ) “明天”(如果活动日期是明天)
  2. "This week" ( If the event lies within this week ) “本周”(如果活动在本周之内)
  3. "Next week" ( If the event lies next week ) “下周”(如果活动在下周举行)
  4. "This month" ( You get the idea ) “这个月”(你明白了)

What is the easiest method of doing this? 最简单的方法是什么? Is there any "gem" out there to help me with this? 有什么“宝石”可以帮助我吗?

The best solution here would be to write your own helper. 最好的解决方案是编写自己的助手。 I'm not going to do the whole thing for you, but this should get you started. 我不会为您做全部,但这应该可以帮助您入门。

Add this to your application_helper.rb : 将此添加到您的application_helper.rb

module ApplicationHelper
  def format_date(date)
    tomorrow = Time.current.beginning_of_day + 1
    day_after_tomorrow = tomorrow + 1
    end_of_week = Time.current.end_of_week

    if date >= tomorrow && date < day_after_tomorrow
      'Tomorrow'
    elsif date >= day_after_tomorrow && date <= end_of_week
      'This week'
    else
      'Some other date'
    end
  end
end

This isn't necessarily the most efficient way of writing this, but I wanted to keep things relatively simple. 这不一定是最有效的编写方法,但是我想使事情保持相对简单。

Then in your view, just use the helper to format your date: 然后,在您的视图中,只需使用助手来设置日期格式即可:

<%= format_date(@event.date) %>

EDIT 编辑

Updated to use Time.current . 更新为使用Time.current Thanks to @house9 for the tip. 感谢@ house9的提示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM