Elliot
Elliot

Reputation: 13835

Rails 3, comparing only the dates of two datetime columns in rails

Lets say I want to compare the dates only of two datetime columns within 1 record. So I don't want the time looked at.

I.e.

viewed_date, and updated_at (I added viewed_date) are two datetime formats, but I only want to see if they occurred on the same day or days apart. The problem with datetime is that its comparing the times, which is just too specific for me right now.

Thanks

-Elliot

Upvotes: 5

Views: 4093

Answers (2)

Ganesh Shrivas
Ganesh Shrivas

Reputation: 157

You can compare only date of object without comparing time like this:-

start_date :-"2015-04-06 15:31:43 +0530"
end_date :- "2015-04-16 15:31:43 +0530 " 
post_review.all.where("(created_at::date >= :start_date) AND 
(created_at::date <= :end_date)", start_date: start_date.strftime("%Y-%m-%d"),end_date: end_date.strftime("%Y-%m-%d"))

Above query gets all the records made between 6 to 16 April

Upvotes: 0

Jakob Borg
Jakob Borg

Reputation: 24425

Declare a new attribute that contains just the date:

class WhateverModel < ActiveRecord::Base
  ...
  def viewed_date_only
    viewed_date.to_date
  end
end

Use that for your comparison in the controller or wherever.

Upvotes: 7

Related Questions