Convert seconds to HH-MM-SS with JavaScript?

前端 未结 30 2094
南旧
南旧 2020-11-22 10:05

How can I convert seconds to an HH-MM-SS string using JavaScript?

30条回答
  •  有刺的猬
    2020-11-22 10:21

    I ran into the case some have mentioned where the number of seconds is more than a day. Here's an adapted version of @Harish Anchu's top-rated answer that accounts for longer periods of time:

    function secondsToTime(seconds) {
      const arr = new Date(seconds * 1000).toISOString().substr(11, 8).split(':');
    
      const days = Math.floor(seconds / 86400);
      arr[0] = parseInt(arr[0], 10) + days * 24;
    
      return arr.join(':');
    }
    

    Example:

    secondsToTime(101596) // outputs '28:13:16' as opposed to '04:13:16'
    

提交回复
热议问题