Getting data from database based on date condition

Hi Everyone,
this is the statement i have, to get all the contents posted from the
database,
@content = Content.find_all
Now, i want to retrieve data (content posted) only for the last 5 days
including current date. Can anyone help me??
My column name is “createdOn” with both Date and Time values stored.

Thanks in advance,
Regards,
Vasanth

Hi,
Use from date_select and to date_select,
and in the controller write the query
@content=Content.find_by _sql(“select * from table where created_on
between to_date(‘2003/01/01’, ‘yyyy/mm/dd’)and to_date (‘2003/12/31’,
‘yyyy/mm/dd’)”)

some thing like this… i hope it will work…

Vasanthakumar C. wrote:

Hi Everyone,
this is the statement i have, to get all the contents posted from the
database,
@content = Content.find_all
Now, i want to retrieve data (content posted) only for the last 5 days
including current date. Can anyone help me??
My column name is “createdOn” with both Date and Time values stored.

Thanks in advance,
Regards,
Vasanth

Naga harish Kanegolla wrote:

Hi,
Use from date_select and to date_select,
and in the controller write the query
@content=Content.find_by _sql(“select * from table where created_on
between to_date(‘2003/01/01’, ‘yyyy/mm/dd’)and to_date (‘2003/12/31’,
‘yyyy/mm/dd’)”)

some thing like this… i hope it will work…

Vasanthakumar C. wrote:

Hi Everyone,
this is the statement i have, to get all the contents posted from the
database,
@content = Content.find_all
Now, i want to retrieve data (content posted) only for the last 5 days
including current date. Can anyone help me??
My column name is “createdOn” with both Date and Time values stored.

Thanks in advance,
Regards,
Vasanth

this may be a little cleaner:

@content = Content.find(:all, :conditions => “created_on <
#{5.days.ago.to_s(:db)}”)

I havent checked that. You may need to reverse the “<” operator.

You could also use a range for the time arg. Example:
@content = Content.find(:all, :conditions => “created_on
#{(5.days.ago…Time.now).to_s(:db)}”)

–jake

Wow… its so simple & worked out for me successfully.
I’ve started liking “Ruby on Rails” more than my old “PHP” code :slight_smile:
Thanks everyone…

Vasanthakumar C. wrote:

Hi Everyone,
this is the statement i have, to get all the contents posted from the
database,
@content = Content.find_all
Now, i want to retrieve data (content posted) only for the last 5 days
including current date. Can anyone help me??
My column name is “createdOn” with both Date and Time values stored.

Thanks in advance,
Regards,
Vasanth

@content = Content.find(:all,
:conditions => [‘created_on > ?’, 5.days.ago])

For future reference, if you had named your field created_on or
created_at, rails would have timestamped it for you.