如何在时间字符串中将毫秒数转换为分钟数?

时间:2018-05-29 13:38:53

标签: javascript

如何舍入变量

var x = '00:00:24.320';
var y = '00:00:19.968';

获得最终结果

x = '00:00:24';
y = '00:00:20';

2 个答案:

答案 0 :(得分:0)

最干净的方法是使用built-in date functionality of JavaScript

function roundToSecond(time) {
    const pad = arg => `${arg}`.padStart(2, '0');
    const date = new Date(`1970-01-01T${time}Z`);
    date.setMilliseconds(date.getMilliseconds() + 500);
    return `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}`;
}

console.log(roundToSecond('00:00:24.320'));
console.log(roundToSecond('00:00:19.968'));
console.log(roundToSecond('23:59:59.501'));

答案 1 :(得分:-1)

拆分,使用toFixed()然后合并

let x = '00:00:24.320';
let [first, second, last] = x.split(':');
last = Number(last).toFixed(0);
x = `${first}:${second}:${last}`;
console.log('x: ', x);