js中时间相关转化

1、将 秒 转化为 时分秒 形式

  可以做倒计时,时间戳相减得到的秒数 转化为时分秒即可

// js文件中   
// 将 秒 化为 时分秒 形式 function formatSeconds(a) { var hh = parseInt(a / 3600) if (hh < 10) hh = '0' + hh var mm = parseInt((a - hh * 3600) / 60) if (mm < 10) mm = '0' + mm var ss = parseInt((a - hh * 3600) % 60) if (ss < 10) ss = '0' + ss var length = hh + ':' + mm + ':' + ss if (a > 0) { return length } else { return '' } } console.log(formatSeconds(3600))

 

2、将 时间戳 转化为 日期(YY-MM-DD HH:mm:ss) 形式

    function formatDate(now) {
      var year = now.getFullYear();
      var month = now.getMonth() + 1;
      var date = now.getDate();
      var hour = now.getHours();
      var minute = now.getMinutes();
      var second = now.getSeconds();
      return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
    }
    //如果记得时间戳是毫秒级的就需要*1000 不然就错了记得转换成整型
    // 原始时间1970-1-15
    var d = new Date(1230999938);
    // 不加参数获取的是当前的时间戳
    var c = new Date()
    alert(formatDate(d));

 

posted @ 2020-04-28 11:19  葡萄想柠檬  Views(217)  Comments(0Edit  收藏  举报
目录代码