js 获取当前时间并格式化

会用到一些各种时间格式化封装,自己记录一下,日后好来翻翻。
b话少说,就是干 ,梭哈。

以下示例(复制即可运行): 

// 获取当前时间并格式化

    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());
 
   //时间戳并格式化 inputTime 参数是毫秒级时间戳
    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;
    }
    console.log(formatDate(1589940954058));
 
 

let date = new Date();   
let strDate = date.toLocaleString().replace(/[年月]/g, '-').replace(/[日上下午]/g, '');
console.log(strDate);

let date = new Date(+new Date() + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/.[d]{3}Z/, '');

console.log(date);

示例:

new Date().toLocaleString('cn',{hour12:false}) //2018/12/6 17:57:15

原文地址:https://www.cnblogs.com/youguo2/p/12935602.html