Search code examples
ruby-on-rails-4timestring-formattingmilliseconds

Having trouble converting milliseconds to a nicely formatted hours, minutes, and seconds string


I’m using Rails 4.2.3. I want to take a time in milliseconds (a duration, not a UTC time) and convert it into hours, minutes and seconds. I’m trying this

    Time.at(time_in_ms).utc.strftime("%H:%M:%S") 

but this doesn’t seem to be working. For instance, in my POstGresql database, I have this amount of milliseconds

3601000

and the above is producing

16:16:40

even though it should produce something like “1:00:01” (one hour and one second). What is the proper way to convert time in milliseconds to a nicely formatted hours, minutes, and seconds?


Solution

  • Time.at() expects a time in seconds after a certain epoch - 1 Jan 1970 00:00:00 UTC - so your code needs to divide the ms figure by 1000 first:

    Time.at(time_in_ms/1000).utc.strftime("%H:%M:%S") 
    

    EDIT: I just rechecked the Ruby docs: the below rider is incorrect! The passed-in number of seconds is assumed to be in UTC, so at() does the calculation THEN factors in the UTC offset. The above .utc undoes that factoring, and is required.


    Of course, the problem with that code then becomes your current time zone. Say you're at UTC-5 (New York time): Time.at(3601000/1000) becomes "01:00:01" local time. Converting it to UTC would subtract five hours from the hour figure, making it "20:00:01". So remove your .utc conversion too:

    Time.at(time_in_ms/1000).strftime("%H:%M:%S")