最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript countdown, formatting seconds to HH:MM:SS - Stack Overflow

programmeradmin4浏览0评论

I have a countdown timer that takes 'seconds' and formats it into HH:MM:SS format. The problem is the second shows 60.

Here's the code I have, this is part of a much larger class. Any suggestions on the best way format so that it doesn't use '60' as a second.

Thank you!

formatSeconds: function (seconds) {

    secondsRemaining = seconds;
    hoursRemaining = Math.floor(secondsRemaining / (60 * 60));
    minutesRemaining = secondsRemaining % (60 * 60);

    hourMinutesRemaining = Math.floor(minutesRemaining / 60);
    minuteSecondsRemaining = minutesRemaining % 60;
    hourSecondsRemaining = Math.ceil(minuteSecondsRemaining);

    fHrs = this.formatNumber(hoursRemaining);
    fMins = this.formatNumber(hourMinutesRemaining);
    fSecs = this.formatNumber(hourSecondsRemaining);

    return fHrs + ':' + fMins + ':' + fSecs;
},

formatNumber: function (number) {
    var s = String(number);
    if (s.length == 1) {
        s = '0' + s;
    }
    return s;
}

I have a countdown timer that takes 'seconds' and formats it into HH:MM:SS format. The problem is the second shows 60.

Here's the code I have, this is part of a much larger class. Any suggestions on the best way format so that it doesn't use '60' as a second.

Thank you!

formatSeconds: function (seconds) {

    secondsRemaining = seconds;
    hoursRemaining = Math.floor(secondsRemaining / (60 * 60));
    minutesRemaining = secondsRemaining % (60 * 60);

    hourMinutesRemaining = Math.floor(minutesRemaining / 60);
    minuteSecondsRemaining = minutesRemaining % 60;
    hourSecondsRemaining = Math.ceil(minuteSecondsRemaining);

    fHrs = this.formatNumber(hoursRemaining);
    fMins = this.formatNumber(hourMinutesRemaining);
    fSecs = this.formatNumber(hourSecondsRemaining);

    return fHrs + ':' + fMins + ':' + fSecs;
},

formatNumber: function (number) {
    var s = String(number);
    if (s.length == 1) {
        s = '0' + s;
    }
    return s;
}
Share Improve this question asked Mar 29, 2012 at 21:28 dzmdzm 23.6k51 gold badges152 silver badges229 bronze badges 3
  • 1 This seems to work as intended? If you pass in 60 you get 00:01:00. jsfiddle/dBLF2/1 – mrtsherman Commented Mar 29, 2012 at 21:36
  • @mrtsherman - Please just answer this with that - It must be something else, thank you. – dzm Commented Mar 29, 2012 at 21:48
  • Just delete your question then. Hope you have it sorted! – mrtsherman Commented Mar 29, 2012 at 22:20
Add a ment  | 

2 Answers 2

Reset to default 10

Update: this is a new version of the previous function. I noticed a bug in the previous version due to floating point rounding errors when the number of seconds was near an hour or minute boundary. Conceptually the math was correct but practically speaking it wasn't when using IEEE-754 number precision.


Here is the function I have written that I use in my code for this purpose:

const formatSeconds = (secs) => {
  const pad = (n) => n < 10 ? `0${n}` : n;

  const h = Math.floor(secs / 3600);
  const m = Math.floor(secs / 60) - (h * 60);
  const s = Math.floor(secs - h * 3600 - m * 60);

  return `${pad(h)}:${pad(m)}:${pad(s)}`;
}

Demo

// Test harness
const demo = () => {
  var seconds = 36005;
  var $output = document.querySelector('.output');

  return () => {
    if (seconds >= 0) {
      $output.innerHTML = `${formatSeconds(seconds)} (${seconds} seconds)`;
      seconds--;
    }
  };
}
setInterval(demo(), 1000);

// The function
const formatSeconds = (secs) => {
  const pad = (n) => n < 10 ? `0${n}` : n;

  const h = Math.floor(secs / 3600);
  const m = Math.floor(secs / 60) - (h * 60);
  const s = Math.floor(secs - h * 3600 - m * 60);

  return `${pad(h)}:${pad(m)}:${pad(s)}`;
}
<div class="output"></div>

Test code

This is a basic test a wrote to validate that this new function works without edge cases.

const formatSeconds = (secs) => {
  const pad = (n) => n < 10 ? `0${n}` : n;

  const h = Math.floor(secs / 3600);
  const m = Math.floor(secs / 60) - (h * 60);
  const s = Math.floor(secs - h * 3600 - m * 60);

  return `${pad(h)}:${pad(m)}:${pad(s)}`;
}

const countSeconds = (str) => {
  const parts = str.split(':');
  const h = parseInt(parts[0], 10);
  const m = parseInt(parts[1], 10);
  const s = parseInt(parts[2], 10);

  return h * 3600 + m * 60 + s;
}

const pare = (secs) => secs === countSeconds(formatSeconds(secs));

var falses = 0;
for (let i = 0; i < 999999; i++) {
  if (pare(i) === false) {
    falses++;
    console.log(`Error: ${i} Seconds`);
  }
}

console.log(`${falses} errors`);

Slight modification to pseudosavant's solution as we don't want the timer to hang on 00:00 for a second while the timer is still running:

var s;
if(h === 0 && m === 0) {
    // last minute only has 59 seconds
    s = Math.ceil((secs / 60) % 1 * 59);
}
else {
    s = Math.floor((secs / 60) % 1 * 60);
}
发布评论

评论列表(0)

  1. 暂无评论