Howto convert seconds to HH:MM:SS

Former Member
Former Member
Hi,

what is the best/correct way to show a seconds-value as HH:MM:SS?

I can't find any helpful methods in the documentation. Maybe it is because I am a beginner.

What be nice if anybody can give me a hint!

cheers
  • function secondsToTimeString(totalSeconds) {
    var hours = (totalSeconds / 3600).toNumber();
    var minutes = ((totalSeconds - hours * 3600) / 60).toNumber();
    var seconds = totalSeconds - hours * 3600 - minutes * 60;
    var timeString = Lang.format("$1$:$2$:$3$", [hours, minutes, seconds]);
    return timeString;
    }

    Otherwise you could also use Toybox::Time::Gregorian (http://developer.garmin.com/downloads/connect-iq/monkey-c/doc/Toybox/Time/Gregorian.html)
  • The above is pretty close. If you want two digits for the hours, minutes, and seconds (as per your requested format HH:MM:SS), the code would be

    var timeString = Lang.format("$1$:$2$:$3$", [
    hours.format("%02d"),
    minutes.format("%02d"),
    seconds.format("%02d")
    ]);


    It is unusual to want a zero padded hour value. In that case the format you want is H:MM:SS, and you could remove the .format("%02d") call that was added to hours.

    Travis
  • Former Member
    Former Member over 10 years ago
    And in fact there is no specific need to bother calculating the subtraction of hours and minutes to get the modulus, because they are all multiples of each other.

    function secondsToTimeString(totalSeconds) {
    var hours = totalSeconds / 3600;
    var minutes = (totalSeconds /60) % 60;
    var seconds = totalSeconds % 60;
    var timeString = format("$1$:$2$:$3$", [hours.format("%01d"), minutes.format("%02d"), seconds.format("%02d")]);
    return timeString;
    }
  • Former Member
    Former Member over 10 years ago
    I'm fine by using the API: (due the fact I need just the convertion from seconds to H:MM:SS
    var options = { :seconds=> totalSeconds };
    var value = Time.Gregorian.duration( options );


    Many thanks for your answers!