首页 > js如何将得到的秒 转成 分:秒这种格式呢?

js如何将得到的秒 转成 分:秒这种格式呢?

如图
比如182转成3:02这种格式


小学生都会做的问题呀


这个得自己写了。

//将时间处理为 2015-2-2 11:45:31 的格式
var formatLocalDate = function(now) {
  if(!now)
    now = new Date();
  else
    now = new Date(now);
  var tzo = -now.getTimezoneOffset(),
      dif = tzo >= 0 ? '+' : '-',
      pad = function(num) {
          norm = Math.abs(Math.floor(num));
          return (norm < 10 ? '0' : '') + norm;
      };
  return now.getFullYear()
    + '-' + pad(now.getMonth()+1)
    + '-' + pad(now.getDate())
    + ' ' + pad(now.getHours())
    + ':' + pad(now.getMinutes())
    + ':' + pad(now.getSeconds());
};

我来发一个最愚蠢的方法,抛砖引玉!

function timeToStr(time) {
    var h = 0,
        m = 0,
        s = 0,
        _h = '00',
        _m = '00',
        _s = '00';
    h = Math.floor(time / 3600);
    time = Math.floor(time % 3600);
    m = Math.floor(time / 60);
    s = Math.floor(time % 60);
    _s = s < 10 ? '0' + s : s + '';
    _m = m < 10 ? '0' + m : m + '';
    _h = h < 10 ? '0' + h : h + '';
    return _h + ":" + _m + ":" + _s;
}

/*
 * 将秒数格式化时间
 * @param {Number} seconds: 整数类型的秒数
 * @return {String} time: 格式化之后的时间
 */ 
function formatTime(seconds) {
    var min = Math.floor(seconds / 60),
        second = seconds % 60,
        hour, newMin, time;

    if (min > 60) {
        hour = Math.floor(min / 60);
        newMin = min % 60;
    }

    if (second < 10) { second = '0' + second;}
    if (min < 10) { min = '0' + min;}

    return time = hour? (hour + ':' + newMin + ':' + second) : (min + ':' + second);
}

// test
console.log(formatTime(182));   // 03:02
console.log(formatTime(12345)); // 03:25:45
【热门文章】
【热门文章】