Search code examples
javascripttypescripttimemilliseconds

JS - Convert Milliseconds into Minutes, Seconds and Hundreths of a second


I am measuring quite precise time and have to convert miliseconds into minutes, seconds and hundreths of a second. Like this: MM:SS.hh Any help is appreciated!


Solution

  • Here's one approach.

    Let's say the number of milliseconds (ms) you need to convert is 123,215.

    Let's start with the number of minutes MM.

    Number of milliseconds in a minute = 1 minute * 60 seconds * 1000 milliseconds
                                       = 60,000
    

    123,215 / 60,000 = 2 (truncate after dividing)

    Hence, there are two full minutes within the original number of milliseconds.

    MM = 2.

    Next, remove a number of milliseconds equivalent to MM from the original number of milliseconds.

    123,215 - (2 * 60,000) = 3,215
    

    Use 3,215 to calculate the number of seconds SS.

    Repeat a similar process here.

    Number of milliseconds in a second = 1 second * 1000 milliseconds = 1,000

    3,215 / 1,000 = 3 (truncate after dividing)

    SS = 3.

    Remove a number of milliseconds equivalent to SS from the original number of milliseconds.

    3,215 - (3 * 1000) = 215

    What you're left with now are what you describe as your hundredths.

    To be more accurate, these are the thousandths that didn't fit into whole seconds.

    So the result of your conversion is :

    02:03:215