Zena Mesfin
Zena Mesfin

Reputation: 421

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?

Upvotes: 4

Views: 1411

Answers (1)

MZaragoza
MZaragoza

Reputation: 10111

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

Upvotes: 8

Related Questions