js获取时间 时分秒

var date = new Date();
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate();
var h = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

按格式输出:2021-08-25 10:02:09

y + "-" + (m < 10 ? ("0" + m) : m) + "-" + (d < 10 ? ("0" + d) : d) + " " + h + ":" + minute + ":" + s;

进一步优化:

date.getFullYear() + '-' + formatNumber(date.getMonth() + 1) + '-' + formatNumber(date.getDate()) + ' ' + h + ':' + minute + ':' + s;
function formatNumber(num) {
    if (num <= 9) {
        return "0" + num;
    } else {
        return "" + num;
    }
}

你可能感兴趣的:(js,html,javascript,css)