Home > Software engineering >  How to get the future nearest time in ruby
How to get the future nearest time in ruby

Time:11-01

Suppose we have current time and then add the 60 munites to the current time.

Time.now   1.hours
# => 2022-11-01 16:47:02.965861  0500

after that we get the next half hour like 17:00:00

I'm able to get the previous half hour time from this code, but unable to find the next half hour time.

time = Time.now - 30.minutes
# => 2022-11-01 15:22:59.942013  0500

Time.at((time.to_time.to_i/1800).round * 1800).to_datetime
# => Tue, 01 Nov 2022 15:00:00  0500

CodePudding user response:

If I understand you correctly, you want to map:

  • 15:00-15:29 to 17:00
  • 15:30-15:59 to 17:30

You could do so with a conditional and advance and change:

t = Time.current

if t.min < 30
  t.advance(hours: 2).change(min: 0)
else
  t.advance(hours: 1).change(min: 30)
end

CodePudding user response:

From what I understand you want to round up the time to the next 30 min mark i.e if it is between 5:01 and 5:29 you want to make it 5:30

For that you can just do

time = Time.now   1.hours
ceil_minutes = 30.minutes

Time.at((time.to_f / ceil_minutes).ceil * ceil_minutes)
  • Related