Rails - Get the time difference in hours, minutes and seconds

前端 未结 5 1043
無奈伤痛
無奈伤痛 2020-12-15 16:17

I\'m looking for an idiomatic way to get the time passed since a given date in hours, minutes and seconds.

If the given date is 2013-10-25 23:55:00 and the current

5条回答
  •  庸人自扰
    2020-12-15 16:58

    Since this has not been marked as duplicate, and the response in the main thread is just way clearer IMHO. I'll add it here for more visibility:

    It can be done pretty concisely using divmod:

    t = (end_time - start_time).round.abs
    mm, ss = t.divmod(60)
    hh, mm = mm.divmod(60)
    puts "%02d:%02d:%02d" % [hh, mm, ss]
    

    You could probably DRY it further by getting creative with collect, or maybe inject, but when the core logic is three lines it may be overkill.

    Note that I've changed a bit the answer to fit better this thread's question.

提交回复
热议问题