Convert seconds to days, hours, minutes and seconds

前端 未结 8 1428
陌清茗
陌清茗 2020-12-03 16:45

I have a Javascript timing event with an infinite loop with a stop button.

It will display numbers when start button is click.Now I want this numbers converted to so

8条回答
  •  攒了一身酷
    2020-12-03 17:16

    function countdown(s) {
    
      const d = Math.floor(s / (3600 * 24));
    
      s  -= d * 3600 * 24;
    
      const h = Math.floor(s / 3600);
    
      s  -= h * 3600;
    
      const m = Math.floor(s / 60);
    
      s  -= m * 60;
    
      const tmp = [];
    
      (d) && tmp.push(d + 'd');
    
      (d || h) && tmp.push(h + 'h');
    
      (d || h || m) && tmp.push(m + 'm');
    
      tmp.push(s + 's');
    
      return tmp.join(' ');
    }
    
    // countdown(3546544) -> 41d 1h 9m 4s
    // countdown(436654) -> 5d 1h 17m 34s
    // countdown(3601) -> 1h 0m 1s
    // countdown(121) -> 2m 1s
    

提交回复
热议问题