js打印当前时间

用js定时打印格式化后的当前日期时间

格式为:YYYY-MM-DD HH:II:SS

//打印格式化当前日期时间的函数
function getDate(){
    let myDate = new Date;
    let year = myDate.getFullYear(); //获取当前年
    let mon = myDate.getMonth() + 1; //获取当前月
    let date = myDate.getDate(); //获取当前日
    let hours = myDate.getHours(); //获取当前小时
    let minutes = myDate.getMinutes(); //获取当前分钟
    let seconds = myDate.getSeconds(); //获取当前秒
    let now = year + "-" + (mon<10?'0'+mon:mon) + "-" + (date<10?'0'+date:date) + " " + (hours<10?'0'+hours:hours) + ":" + (minutes<10?'0'+minutes:minutes) + ":" + (seconds<10?'0'+seconds:seconds);
    console.log(now);
}
//定时每秒钟调用一次
var tLoop = window.setInterval(getDate,1000);
//关闭定时调用
window.clearInterval(tLoop);