Eric Goodwin

Rails, Databases and Dates
06/01/24

On one of the projects that I am working on at the moment I am doing alot of work with dates and events. I’ve had to write quite a few find_by_sql for some of my more complicated queries and a nice little rails date helper has come in handy.

#Time
1.year.ago.to_s(:db) 
#=> '2005-01-24 15:29:24'
Time.now.last_month.to_s(:db) 
#=> '2005-12-24 15:29:24'

#Time Range
(Time.now..Time.utc(2006, 12, 24, 09, 00)).to_s(:db)
#=>'BETWEEN 2005-01-24 15:29:24' AND '2006-12-24 09:00:00'", 

#Date
Date.today.to_s(:db) 
#=> '2006-01-24'
5.days.from_now.to_date.to_s(:db) 
#=> '2006-01-29'

#Date Range
(Date.today..1.year.ago.to_date).to_s(:db) 
#=> "BETWEEN '2006-01-24' AND '2005-01-24'"
Update: This one doesn’t have much to do with the database at all, but it’s still a very handy function
#Get last day of March 2006
Time.days_in_month 3, 2006 #=> 31

1 comment

Comments

  1. 08/03/18 - John Griffiths Says:

    Excellent, was hunting around how to do this, good post!

Have your say

A name is required. You may use HTML in your comments.




About

Eric Goodwin is a web developer living in Victoria BC, Canada. You can contact him at eric@ericgoodwin.com

Open Source

Projects

Elsewhere

Archives