Sankalp Singha
Sankalp Singha

Reputation: 4546

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?

Upvotes: 1

Views: 89

Answers (1)

Jon
Jon

Reputation: 10898

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:

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. Thanks to @house9 for the tip.

Upvotes: 4

Related Questions