How to convert time milliseconds to hours, min, sec format in JavaScript?

后端 未结 16 2384
渐次进展
渐次进展 2020-11-29 02:28

I have the time as milliseconds, but I want the time after conversion like 00:00:00.

Ex: In milliseconds=86400000. I want how many hours in that millise

16条回答
  •  情话喂你
    2020-11-29 03:09

    Sorry, late to the party. The accepted answer did not cut it for me, so I wrote it myself.

    Output:

    2h 59s
    1h 59m
    1h
    1h 59s
    59m 59s
    59s
    

    Code (Typescript):

    function timeConversion(duration: number) {
      const portions: string[] = [];
    
      const msInHour = 1000 * 60 * 60;
      const hours = Math.trunc(duration / msInHour);
      if (hours > 0) {
        portions.push(hours + 'h');
        duration = duration - (hours * msInHour);
      }
    
      const msInMinute = 1000 * 60;
      const minutes = Math.trunc(duration / msInMinute);
      if (minutes > 0) {
        portions.push(minutes + 'm');
        duration = duration - (minutes * msInMinute);
      }
    
      const seconds = Math.trunc(duration / 1000);
      if (seconds > 0) {
        portions.push(seconds + 's');
      }
    
      return portions.join(' ');
    }
    
    console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) + (59 * 1000)));
    console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000)              ));
    console.log(timeConversion((60 * 60 * 1000)                                 ));
    console.log(timeConversion((60 * 60 * 1000)                    + (59 * 1000)));
    console.log(timeConversion(                   (59 * 60 * 1000) + (59 * 1000)));
    console.log(timeConversion(                                      (59 * 1000)));
    

提交回复
热议问题