Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do get a random DateTime rounded to beginning of hour in Rails?

Basically I'd like to get a random datetime within the last year:

rand(1.year).ago  #=> Sun, 22 Sep 2013 18:37:44 UTC +00:00 (example)

But how do I go about specifying or limiting this to times on the hour? For example:

Sun, 22 Sep 2013 18:00:00 UTC +00:00
Sat, 02 Nov 2013 10:00:00 UTC +00:00
Fri, 12 Apr 2013 21:00:00 UTC +00:00
like image 726
Sheldon Avatar asked Dec 27 '13 18:12

Sheldon


3 Answers

I finally found what I was looking for. @Stoic's answer is very good but I found this available method (http://api.rubyonrails.org/classes/DateTime.html):

rand(1.year).ago.beginning_of_hour

Does exactly the same thing but looks neater and prevents you from having to write your own function.

like image 171
Sheldon Avatar answered Nov 10 '22 03:11

Sheldon


Rounding datetime to the nearest hour in Rails would be

(DateTime.now + 30.minutes).beginning_of_hour

Not the answer to the actual question, but it does answer the title of the question (which is how i got here).

like image 23
andorov Avatar answered Nov 10 '22 03:11

andorov


Try this:

def random_time_to_nearest_hour
  time = rand(1.year).ago
  time - time.sec - 60 * time.min
end

Examples:

[1] pry(main)> random_time_to_nearest_hour
=> Sun, 28 Apr 2013 16:00:00 UTC +00:00
[2] pry(main)> random_time_to_nearest_hour
=> Sat, 08 Jun 2013 15:00:00 UTC +00:00
[3] pry(main)> random_time_to_nearest_hour
=> Thu, 22 Aug 2013 23:00:00 UTC +00:00
[4] pry(main)> random_time_to_nearest_hour
=> Tue, 29 Jan 2013 14:00:00 UTC +00:00
[5] pry(main)> random_time_to_nearest_hour
=> Tue, 13 Aug 2013 06:00:00 UTC +00:00
[6] pry(main)> random_time_to_nearest_hour
=> Mon, 03 Jun 2013 08:00:00 UTC +00:00
[7] pry(main)>

Note that, this method will always floor down to the nearest hour, but since you are anyways generating a random time, it wont matter if this time is getting floor'ed down or getting round'ed. :)

like image 32
Stoic Avatar answered Nov 10 '22 04:11

Stoic