20

I need to perform the following conversion:

0     -> 12.00AM
1800  -> 12.30AM
3600  -> 01.00AM
...
82800 -> 11.00PM
84600 -> 11.30PM

I came up with this:

(0..84600).step(1800){|n| puts "#{n.to_s} #{Time.at(n).strftime("%I:%M%p")}"}

which gives me the wrong time, because Time.at(n) expects n to be number of seconds from epoch:

0     -> 07:00PM
1800  -> 07:30PM
3600  -> 08:00PM
...
82800 -> 06:00PM
84600 -> 06:30PM

What would be the most optimal, time zone independent solution for this transformation?

4 Answers 4

42

The simplest one-liner simply ignores the date:

Time.at(82800).utc.strftime("%I:%M%p")

#-> "11:00PM"
4
  • 2
    NB: If someone came here looking for an answer to get a way to convert any number of seconds (even high counts which spans days) into an ever increasing HH:MM:SS counter (not just limited to a 24 hour span), then this answer is not the solution to that. Ignoring the date, like this answer suggest, will make the HH counter be reset to 00 whenever going across day boundaries.
    – Magne
    Sep 8, 2017 at 11:32
  • @Magne Your note was meant for me. Now, do you have a suggestion for a solution for an ever increasing HH:MM:SS? Dec 4, 2020 at 20:58
  • 1
    @JoshuaPinter yes, I found my solution and posted it as an answer here for you now: stackoverflow.com/a/65166238/380607
    – Magne
    Dec 6, 2020 at 8:47
  • Not working if hours is > 24
    – fguillen
    Sep 19, 2023 at 10:08
3

Not sure if this is better than

(Time.local(1,1,1) + 82800).strftime("%I:%M%p")


def hour_minutes(seconds)
  Time.at(seconds).utc.strftime("%I:%M%p")
end


irb(main):022:0> [0, 1800, 3600, 82800, 84600].each { |s| puts "#{s} -> #{hour_minutes(s)}"}
0 -> 12:00AM
1800 -> 12:30AM
3600 -> 01:00AM
82800 -> 11:00PM
84600 -> 11:30PM

Stephan

1
  • It's nice and short, but I think "toClock" does the more direct calculations and looks more reliable. Except "toClock" should reject negative inputs, and perform "% 86400" on the input. Oct 19, 2010 at 16:28
2

Two offers:

The elaborate DIY solution:

def toClock(secs)
  h = secs / 3600;  # hours
  m = secs % 3600 / 60; # minutes
  if h < 12 # before noon
    ampm = "AM"
    if h = 0
      h = 12
    end
  else     # (after) noon
    ampm =  "PM"
    if h > 12
      h -= 12
    end
  end
  ampm = h <= 12 ? "AM" : "PM";
  return "#{h}:#{m}#{ampm}"
end

the Time solution:

def toClock(secs)
  t = Time.gm(2000,1,1) + secs   # date doesn't matter but has to be valid
  return "#{t.strftime("%I:%M%p")}   # copy of your desired format
end

HTH

2

In other solutions, the hour-counter would be reset to 00 when crossing 24-hour day boundaries. Also beware that Time.at rounds down, so it will give the wrong result if the input has any fractional seconds (f.ex. when t=479.9 then Time.at(t).utc.strftime("%H:%M:%S") will give 00:07:59 and not 00:08:00` which is the correct one).

If you want a way to convert any number of seconds (even high counts larger than 24-hour day spans) into an ever increasing HH:MM:SS counter, and handle potential fractional seconds, then try this:

# Will take as input a time in seconds (which is typically a result after subtracting two Time objects),
# and return the result in HH:MM:SS, even if it exceeds a 24 hour period.
def formatted_duration(total_seconds)
  total_seconds = total_seconds.round # to avoid fractional seconds potentially compounding and messing up seconds, minutes and hours
  hours = total_seconds / (60*60)
  minutes = (total_seconds / 60) % 60 # the modulo operator (%) gives the remainder when leftside is divided by rightside. Ex: 121 % 60 = 1
  seconds = total_seconds % 60
  [hours, minutes, seconds].map do |t|
    # Right justify and pad with 0 until length is 2. 
    # So if the duration of any of the time components is 0, then it will display as 00
    t.round.to_s.rjust(2,'0')
  end.join(':')
end

Modified from @springerigor's and suggestion in the discussion at https://gist.github.com/shunchu/3175001

3
  • 1
    Nicely done! I ended up rolling my own that utilized ActiveSupport::Duration.build( seconds ).parts but I like yours so much because it's simpler and doesn't require a Rails that I'm scrapping mine and replacing it with yours. Thanks for posting! Dec 6, 2020 at 15:45
  • I also cross-posted to this gist, which seemed to get a lot of traction: gist.github.com/shunchu/3175001#gistcomment-3552126 Dec 6, 2020 at 15:53
  • 1
    Whoops, my bad. Didn't realize it was the same gist. I've gone ahead and removed my comment on that Gist. Thanks again. Dec 8, 2020 at 16:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.