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
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.
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
精彩评论