JS将秒数转为HH:MM:SS格式

2017-12-19  本文已影响157人  云淡风轻的成长

将24小时内的秒数转化为HH:MM:SS格式,分为大于60秒和小于等于60秒。

_changeTimeBySecond(second) {
  var hourTime = 0;
  var minuteTime = 0;
  var secondTime = 0;
  if (second > 60) {  //如果秒数大于60
    minuteTime = Math.floor(second / 60);
    secondTime = Math.floor(second % 60);
    if (minuteTime >= 60) {  //如果分钟大于60
      hourTime = Math.floor(minuteTime / 60);
      minuteTime = Math.floor(minuteTime % 60);
    } else {
      hourTime = 0;
    }
  } else {
    hourTime = 0;
    minuteTime = 0;
    if (second == 60) {  //如果秒数等于60
      minuteTime = 1;
      secondTime = 0;
    } else {
      secondTime = second;
    }
  }
  var timeResult = this._addZero(hourTime) + ':' +this._addZero(minuteTime) + ':' + this._addZero(secondTime);
  return timeResult;
}

补零操作

_addZero(time) {
  let str = time;
  if (time < 10) {
    str = '0' + time;
  }
  return str;
}
上一篇下一篇

猜你喜欢

热点阅读