timpone
timpone

Reputation: 19969

How to round down a DateTime value

I have a Location that can have Events. I want to have an upcoming_events method but want it to round down such that if someone looks at 10pm at night, it will show todays events. I have this:

def upcoming_events
  d=Time.new
  d.strftime("%m-%d-%Y")
  l=Event.where('location_id=? and start_datetime>?',self.id, d)
end

I gets converted down correctly but in d.strftime but the query is:

SELECT `events`.* FROM `events` WHERE (location_id=301 and start_datetime>'2012-06-20 02:49:23')

Any idea how to just get it to do '2012-06-20'?

Upvotes: 2

Views: 1034

Answers (2)

creemama
creemama

Reputation: 6665

I think you actually meant "%Y-%m-%d" vice "%m-%d-%Y" since you wanted '2012-06-20'. As such, try the following:

def upcoming_events
  d=Time.new
  l=Event.where('location_id=? and start_datetime>?', self.id, d.strftime("%Y-%m-%d"))
end

Upvotes: 1

Andrew Marshall
Andrew Marshall

Reputation: 96994

Calling strftime does essentially nothing here, since it doesn't change the d object in any way.

Anyway, Rails provides the method beginning_of_day on DateTime (as well as Date & Time) that does exactly what you want:

d = Time.now        #=> 2012-06-19 23:05:54 -0400
d.beginning_of_day  #=> 2012-06-19 00:00:00 -0400

So just change your code to:

Event.where('location_id=? and start_datetime>?', self.id, d.beginning_of_day)

Upvotes: 6

Related Questions