Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to the nearest half an hour or hour in ruby fake time?

I am using fake time to display in my UI. I am manipulating the time to be random like this.

  date: Time.zone.now - (i % 9).days - rand(3).days - rand(2).hours + rand(60).minutes

However I would like to round to the nearest hour that is 3.35 pm becomes 3.30

do you know how I can do that?

like image 228
Zena Mesfin Avatar asked Sep 19 '25 23:09

Zena Mesfin


1 Answers

You can extend the time class with this method I normally do this in the lib/core_ext directory

# lib/core_ext/time.rb
class Time
  def round_off(seconds = 60)
    Time.at((self.to_f / seconds).round * seconds)
  end
end

now you can do something like

time = Time.zone.now - rand(3).days - rand(2).hours + rand(60).minutes
time.round_off(30.minutes)

I hope that this is able to help you

like image 160
MZaragoza Avatar answered Sep 22 '25 14:09

MZaragoza