将毫秒数从3位更改为2位数

时间:2016-01-03 23:48:55

标签: javascript datetime

制作秒表只能使用2位数作为毫秒部分。我有完整的JSFiddle here。我可以使用的函数是formatter()方法。

现在,方法如下:

formatter(timeInMilliseconds) {
  const padZero = (time) => {
    while (time.length < 2) { 
      time = '0' + time; 
    } 
    return time;
  }

  let time = new Date(timeInMilliseconds);
  let minutes = padZero(time.getMinutes().toString());
  let seconds = padZero(time.getSeconds().toString());
  let milliseconds = padZero((time.getMilliseconds() / 10).toFixed(0));

  let output = `${minutes} : ${seconds} . ${milliseconds}`;
  console.log(output);
  return output;
} 

在大多数情况下,它有效。如果你在计时器运行时查看我的JSFiddle的控制台,问题就很明显了。例如,如果秒表目前处于类似00 : 15 . 99的状态,则它会在下一个时刻而不是00 : 15 . 100变为00 : 16 . 00

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:3)

toFixed轮次而不是截断,因此995毫秒及以上将变为99.5并被100格式化为toFixed。您可以将其转换为整数,然后转换为字符串,而不是截断它:

let milliseconds = padZero('' + (time.getMilliseconds() / 10 | 0));

使padZero接受数字而不是字符串也可能是一个很好的简化:

function padZero(time) {
    return time < 10 ? '0' + time : '' + time;
}

let time = new Date(timeInMilliseconds);
let minutes = padZero(time.getMinutes());
let seconds = padZero(time.getSeconds());
let milliseconds = padZero(time.getMilliseconds() / 10 | 0);

let output = `${minutes} : ${seconds} . ${milliseconds}`;

最后,如果timeInMilliseconds不是自1970-01-01 00:00:00 UTC以来的时间戳(以毫秒为单位),而是持续时间,则将其转换为Date是不合适的。做一些数学运算:

const minutes = padZero(timeInMilliseconds / 60000 | 0);
const seconds = padZero((timeInMilliseconds / 1000 | 0) % 60);
const centiseconds = padZero((timeInMilliseconds / 10 | 0) % 100);

答案 1 :(得分:2)

你的问题是.toFixed()轮而不是截断。

(99.4).toFixed(0) == '99'
(99.5).toFixed(0) == '100'

您需要做的就是替换

(time.getMilliseconds() / 10).toFixed(0)

Math.floor(time.getMilliseconds() / 10).toFixed(0)

它会起作用。

答案 2 :(得分:0)

您可以使用substring()

let milliseconds = padZero((time.getMilliseconds() / 10).toFixed(0)).substr(0, 2);
相关问题