以小时和分钟(00:00)和圆秒到分钟显示时间

时间:2016-08-11 13:26:52

标签: javascript angularjs jsfiddle

我希望时间总是在小于10时显示0:如果任务需要3小时7分33秒,它将显示为03:08

现在我点击它们后按钮被禁用,这样你就无法重启计时器

这是JS代码

value

这是HTML

value

3 个答案:

答案 0 :(得分:0)

您需要将+((timer.now() - startTime) / 1000 > 30)添加到totalMinutes,然后您需要计算mod 60JSFiddle

let startTime;

const timer = typeof performance !== `undefined` && typeof performance.now === `function` ? performance : Date;
const startButton = document.getElementById('start');
const stopButton = document.getElementById('stop');
const display = document.getElementById('display');

startButton.onclick = () => {
    startTime = timer.now();
  startButton.disabled = "disabled";
};

stopButton.onclick = () => {
  var totalSeconds = Math.round((timer.now() - startTime) / 1000);
  var totalMinutes = Math.floor(totalSeconds / 60 + +((timer.now() - startTime) / 1000 > 30));
  var totalHours = Math.floor(totalSeconds / 60 / 60);
  var displaySeconds = totalSeconds % 60;
  var displayMinutes = totalMinutes % 60;
  var strDisplayTime = 
    (totalHours > 0 ? (totalHours + '0:') : '') + 
    (displayMinutes > 0 || totalHours > 00 ?
        ((displayMinutes >= 10 ? '' : '0') + displayMinutes + ':') : '00:00:') +
    ((displaySeconds >= 10 ? '' : '0') + displaySeconds)  
    display.innerHTML = strDisplayTime;
  stopButton.disabled = "disabled";
};

答案 1 :(得分:0)

试试这个:

var fixedDisplaySeconds = ( '0' + displaySeconds ).substr( -2 );
var fixedDisplayMinutes = ( '0' + displayMinutes ).substr( -2 );
var fixedStrDisplayTime = fixedDisplaySeconds + ':' + fixedDisplayMinutes;

基本上,始终在开头添加'0',然后获取最后2个字符 - 如果时间为1,则'0' + 1 = '01' - 最后2个字符为'01'。然后,如果时间为11,则'0' + 11 = '011' - 获取最后2个字符,然后获得'11'

答案 2 :(得分:0)

您可以直接从毫秒计数器创建日期,并使用.getUTCHours()getUTCMinutes()方法将其格式化为HH:MM

// 3h07m33s in milliseconds
var ms = (3 * 3600 + 7 * 60 + 33) * 1000;

// create date (in the year 1970, which is OK)
var d = new Date(ms + 30000);

// format date as HH:MM
var strDisplayTime =
  ('0' + d.getUTCHours()).slice(-2) + ':' +
  ('0' + d.getUTCMinutes()).slice(-2);

console.log(strDisplayTime);

对于支持它的浏览器,您也可以使用.toLocaleString()。但它在这里看起来不是一个非常有趣的选择。

// 3h07m33s in milliseconds
var ms = (3 * 3600 + 7 * 60 + 33) * 1000;

// create date (in the year 1970, which is OK)
var d = new Date(ms + 30000);

// format date as HH:MM
var strDisplayTime = d.toLocaleString(
  'en-US',
  {
    timeZone: 'UTC',      // we've created a UTC Date, so we must display it as such
    hour12  : false,      // use 24-hour format
    hour    : '2-digit',  // display hours as two digits
    minute  : '2-digit'   // display minutes as two digits
  }
);

console.log(strDisplayTime);