isabellabrookes
isabellabrookes

Reputation: 83

Compare date_time with today's date

I’m trying to compare a saved date_field with today’s date. Seems to work in console but I can't make it work in my code.

  <% @flights.each do |flight| %>
    <% if (Time.new("%Y-%m-%d") < flight.flight_date) %>
      <tr class="active">
    <% else %>
      <tr class="success">
    <% end %> 

Thanks to @drenmi for the patient answers and explaining why that my date_field was saved as a datetime attribute hence Time.now working and not Date.today. Now to fix my naming so I follow convention!

Upvotes: 1

Views: 2456

Answers (3)

Tu ..
Tu ..

Reputation: 29

Time.now.utc 

this is the best choice

time = Time.now.utc.iso8601

Time.iso8601(time)

...

don't forget: require 'time'

Upvotes: 0

Drenmi
Drenmi

Reputation: 8777

Using Time.new("%Y-%m-%d") will produce an empty Time object:

Time.new("%Y-%m-%d")
# => 0000-01-01 00:00:00 +0730

What you want to do is compare to Time.now:

<% if Time.now < flight.flight_date %>

Or, if using Rails, you might want to use Time.current, or Date.current:

<% if Date.current < flight.flight_date %>

or

<% if Time.current < flight.flight_date %>

Upvotes: 2

mohammad mahmoodi
mohammad mahmoodi

Reputation: 185

you want using Date.today in rails

Upvotes: 2

Related Questions