js獲取當前時間,並格式化爲"yyyy-MM-dd HH:mm:ss"

/**
 * Created by Administrator on 2019/11/15.
 *指尖敲打着世界 ----一個陽光而又不失帥氣的少年!!!.
 */
// js獲取當前時間,並格式化爲"yyyy-MM-dd HH:mm:ss"
function getFormatDate() {
    var date = new Date();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentDate = date.getFullYear() + "-" + month + "-" + strDate
        + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return currentDate;
}

console.log(getFormatDate());//2019-11-15 15:26:49
//將時間戳轉換成 yyyy-MM-dd HH:mm:ss
// putTime 參數是毫秒級時間戳

function formatDate(inputTime) {
    var date = new Date(inputTime);
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    h = h < 10 ? ('0' + h) : h;
    var minute = date.getMinutes();
    var second = date.getSeconds();
    minute = minute < 10 ? ('0' + minute) : minute;
    second = second < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}

var time = new Date().getTime();

console.log(formatDate(time));//2019-11-15 15:26:49
相關文章
相關標籤/搜索