title: Rails datetime comparison
body: <p>My application offers the opportunity to create events with a start date and an end date with a certain format. Events should not last longer than two weeks, so the events controller check this condition with a <code>before_action</code>:</p>
  
  <pre><code>def correct_time
    @event = current_user.events.build(event_params)
    if (@event.end_time.to_datetime - @event.start_time.to_datetime) &gt; 2.weeks
      flash[:danger] = "Attention! Events cannot last longer than 2 weeks"
      redirect_to root_url
    end
  end
  </code></pre>
  
  <p>So I was puzzled when I was able to create the following event, which lasts 22 days:</p>
  
  <pre><code>&gt;&gt; event = Event.last
  =&gt; #&lt;Event id: 1, user_id: 1, place: "barcelona", start_time: "2017-12-24 10:26", end_time: "2018-01-15 10:26", created_at: "2017-12-15 09:27:13", updated_at: "2017-12-15 09:27:13"&gt;
  </code></pre>
  
  <p>Apparently the condition does not work because Rails mistakes days with seconds:</p>
  
  <pre><code>&gt;&gt; (event.end_time.to_datetime - event.start_time.to_datetime)
  =&gt; (22/1)
  
  &gt;&gt; (event.end_time.to_date - event.start_time.to_date) &gt; 2.weeks
  =&gt; false
  
  &gt;&gt; (event.end_time.to_datetime - event.start_time.to_datetime) == 22.days
  =&gt; false
  
  &gt;&gt; (event.end_time.to_datetime - event.start_time.to_datetime) == 22.seconds
  =&gt; true
  </code></pre>
  
  <p>I do not know why this happens and how to solve it, apart from using <code>14.seconds</code> instead of <code>2.weeks</code> in the above expression, but that would not be correct.</p>