Rounding Hours - Ruby
A year ago I found myself in need of having to round hours in a rails application. I asked the question on - Stack Overflow and it's been one of my most up-voted answers.
My dilemma was rounding a specified time to the hour for test data (and for other reasons I can't quite remember..). However, I thought I'd share the tip as it provided me with my first gold badge on SO.
The original answer suggested creating a custom function:
def random_time_to_nearest_hour time = rand(1.year).ago time - time.sec - 60 * time.min end
But as luck would have it, RoR comes with a DateTime object that includes the function beginningofhour:
rand(10).years.ago.beginning_of_hour #Mon, 09 Nov 2009 23:00:00 UTC +00:00
Also worth noting that the DateTime object comes with a few more useful methods that could save you some 'time'.
rand(10).years.ago.end_of_day #Sun, 09 Nov 2008 23:59:59 UTC +00:00 rand(10).years.ago.midday #Thu, 09 Nov 2006 12:00:00 UTC +00:00
For a full list of methods read the docs - docs