Convert milliseconds to hours:minutes:seconds

I have a value in milliseconds that I would like to display as hours:minutes:seconds in a datafield.

Is there some built in functionality to do that conversion?

The millisecond value may be both negative (behind) or positive (ahead).
  • I have a value in milliseconds that I would like to display as hours:minutes:seconds in a datafield.

    Is there some built in functionality to do that conversion?

    The millisecond value may be both negative (behind) or positive (ahead).


    I would guess, you want something like this:

    using Toybox.Time as Time;

    var curr_milli = Time.now().value() + milliseconds;
    var tinfo = Time.Gregorian.info(new Time.Moment(curr_milli), Time.FORMAT_SHORT);
    var text = tinfo.hour.format("%02d") + ":" + tinfo.min.format("%02d") + ":" + tinfo.sec.format("%02d");


    Edit: ok, I see, you meant it not relative to the current time.
  • Here's my standard function to convert seconds into a string of hh:mm:ss, and I use it for ms by just dividing ms by 1000:
    time=toHMS(info.timerTime/1000);
    for example
    function toHMS(secs) {
    var hr = secs/3600;
    var min = (secs-(hr*3600))/60;
    var sec = secs%60;
    return hr.format("%02d")+":"+min.format("%02d")+":"+sec.format("%02d");
    }


    as you said you may have a neg number, when you start you want to have something like

    var aSec=secs.abs();

    and then use aSec where I use secs.

    Then at the end, check if secs<0 and if so, put a "-" are the beginning of the string before returning it.
  • I have assumed you want to identify if it is a negative value
    //var msValue = ......
    var sign = "";
    if (msValue < 0) {
    sign = "-";
    msValue *= -1;
    }
    var hours = msValue / 1000 / 60 / 60;
    var mins = (msValue / 1000 / 60) % 60;
    var secs = (msValue / 1000) % 60;
    var timeStr = Lang.format("$1$$2$:$3$:$4$", [sign, hours.format("%01d"), mins.format("%02d"), secs.format("%02d")]);
  • sharkbait_au - Seems we think alike! :)
  • Possibly. Except will modulus work on a negative number? Ah, I see your update :)
  • I think you can mod a negative, but I don't think I've tried it with mc.
  • You can mod a negative, but it will give you a negative result. i.e., -111 % 60 = -51.

    Travis
  • Travis - that's what I figured would happen as that's the way I've seen it in other languages. I just wasn't sure if mc wouldn't throw an exception on it for some reason..