Trying to get records that were created this year, I stumbled upon this great question. The second answer says you get all records from a model that were created today by saying:
Model.where("created_at >= ?", Time.now.beginning_of_day)
So, naturally, I tried the same thing with Time.now.beginning_of_year, and it works just fine.
However, what struck me as interesting is that the outputted query (I tried it in the console) is
SELECT COUNT(*) FROM `invoices` WHERE (created_at >= '2012-12-31 23:00:00')
I wasn’t aware that 2013 already began at 2012-12-31 23:00:00? How’s that?
If you haven’t set it yet, you should set your timezone in the
config/application.rbfile. Look for the line that begins withconfig.time_zone. (If you aren’t sure what value to give, you can runrake time:zones:allto get a list of all available timezones.)Once you’ve set your timezone, you should use
Time.zone.now, as opposed toTime.now. This will properly “scope” your times to your timezone.Check the API for more details on
TimeWithZone.