js中实现获取当前的具体时间
function getCurrentTime() {
let nowTime = new Date(),
year = nowTime.getFullYear(),
month = nowTime.getMonth() + 1 >= 10 ? nowTime.getMonth() + 1 : '0' + (nowTime.getMonth() + 1),
day = nowTime.getDate() >= 10 ? nowTime.getDate() : '0' + nowTime.getDate(),
hours = nowTime.getHours() >= 10 ? nowTime.getHours() : '0' + nowTime.getHours(),
minute = nowTime.getMinutes() >= 10 ? nowTime.getMinutes() : '0' + nowTime.getMinutes(),
second = nowTime.getSeconds() >= 10 ? nowTime.getSeconds() : '0' + nowTime.getSeconds(),
currentTime = "";
currentTime = year + '-' + month + '-' + day + " " + hours + ":" + minute + ":" + second;
return currentTime;
}
getCurrentTime(); //"2020-10-30 14:05:38"
利用js简单却快速的实现这个小小的功能。如果是打印每一秒的时间呢,那我们不妨给上面的方法添加一个调取的定时器:
function getCurrentTime() {
let nowTime = new Date(),
year = nowTime.getFullYear(),
month = nowTime.getMonth() + 1 >= 10 ? nowTime.getMonth() + 1 : '0' + (nowTime.getMonth() + 1),
day = nowTime.getDate() >= 10 ? nowTime.getDate() : '0' + nowTime.getDate(),
hours = nowTime.getHours() >= 10 ? nowTime.getHours() : '0' + nowTime.getHours(),
minute = nowTime.getMinutes() >= 10 ? nowTime.getMinutes() : '0' + nowTime.getMinutes(),
second = nowTime.getSeconds() >= 10 ? nowTime.getSeconds() : '0' + nowTime.getSeconds(),
currentTime = "";
currentTime = year + '-' + month + '-' + day + " " + hours + ":" + minute + ":" + second;
console.log(currentTime);
}
var time = setInterval(function(){
getCurrentTime();
},1000);