Converting Seconds to Midnight Back to Time

Rails has a nice little function for it’s DateTime class called ‘seconds_since_midnight’. Super handy if you (for some reason) just want to store time, without a date in your database. However, here is the next problem you will come across: how do I display this value of seconds as an actual, human-readable time?

Luckily, this is simple:

def convert_to_time_from_second_to_midnight(seconds)
  hh, mm = seconds.divmod(60)[0].divmod(60)
  Time.parse(’%d:%d’ % [hh, mm]).strftime(”%I:%M %p”)
end

divmod is an interesting little function that I’ve never used prior to writing this.  It’s very simple: just returns the quotient and the modulus. It helps us get the hours and minutes within just one line. Then all we have to do is format it and the result is a nicely formatted time like so “12:30 PM”.