Today I Learned

hashrocket A Hashrocket project

Rounding Time in Increments

I Recently needed to round down a time in certain increments. This is not something I've ever been asked to do previously so it was an interesting problem to figure out. The resulting formula is simple:

TIME_MIN - (TIME_MIN % INCREMENT)

This will give you the previous incremental minute. ex: Given a 5 minute increment @ 3:12, the result would be 10.

time = Time.now
new_min = time.min - (time.min % 5)

I happen to be solving this in a project with ActiveSupport so there was access to Time#change so I finished this up with:

time.change(min: new_min)
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.