时间戳转化为时间&&截取时间的年月日

时间戳转化为正常的时间格式

function formatDate(date, fmt) {
    if (/(y+)/.test(fmt)) {
        // 在这里 date.getFullYear() + '' 是为了把拿到的年份转化为字符串
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
    };
    for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
            let str = o[k] + '';
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
        }
    }
    return fmt;
};

function padLeftZero(str) {
    return ('00' + str).substr(str.length);
}

var a = new Date(1469261964000);
console.log(formatDate(a,'yyyy-MM-dd hh:mm'))   //2016-07-23 16:19
console.log(formatDate(a,'yyyy-MM-dd'))  // 2016-07-23

截取时间 2016-07-23 16:19:00 的年月日

var reg = /^(d{4})-(d{1,2})-(d{1,2})s(d{1,2})(:(d{1,2})){2}$/;
var time = '2016-07-23 16:19:00';
var end = time.match(reg).slice(1,4).join('-');
console.log(end)   // 2016-07-23
原文地址:https://www.cnblogs.com/lan1974/p/8981517.html