2

I'm trying to round the current time to the closest 15-min increment.

For example, if the current time is "4:37pm", I want it to round to "4:30pm". And if it were "4:41pm", it should round to "4:45pm".

The reason for this is I have an HTML select that has 15-min increments, and I want to default it to select the closest option based on time.

I've come across some code that works, but it seems clunky:

increment = 15*60                                          # => 900 (15 min in seconds)
current_time = Time.zone.now                               # => Mon, 27 Aug 2018 17:50:31 EDT -04:00
Time.at((current_time.to_r / increment).round * increment) # => 2018-08-27 17:45:00 -0400

I'm surprised there's not a built-in time function like Time.now.round_to_closest(increment_in_min: 15)

Is it there and I'm just missing it?

Dan L
  • 4,319
  • 5
  • 41
  • 74
  • You could write that method, using the code that works, and add it to Time as a refinement? – David Aldridge Aug 27 '18 at 22:00
  • 3
    Possible duplicate of [How to round a time down to the nearest 15 minutes in Ruby?](https://stackoverflow.com/questions/449271/how-to-round-a-time-down-to-the-nearest-15-minutes-in-ruby) – dinjas Aug 27 '18 at 22:35
  • @dinjas: I think you are correct that this is a duplicate of that question. Should I close/delete this question or is there a process for linking/merging similar questions? – Dan L Aug 27 '18 at 22:54
  • Flag it as duplicate and it will get linked to the other question in the header. There is no need to delete the question. – 3limin4t0r Aug 27 '18 at 23:40

1 Answers1

2

It may seem clunky because you have to do some math on a couple of lines there, but that looks like a great solution to me. Sometimes you have to forego elegance for functionality.

matty_keene
  • 158
  • 2
  • 8