js 格式化时间

function formatTime (time, format) {
    time = typeof(time) === "number" ? time : (time instanceof Date ? time.getTime() : parseInt(time));
    if(isNaN(time)) return null;
    if(typeof(format) !== 'string' || !format) format = 'yyyy-MM-dd hh:mm:ss';
    let _time = new Date(time);
    time = _time.toString().split(/[\s\:]/g).slice(0, -2);
    time[1] = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'][_time.getMonth()];
    let _mapping = { MM: 1, dd: 2, yyyy: 3, hh: 4, mm: 5, ss: 6 };
    return format.replace(/([Mmdhs]|y{2})\1/g, (key) => time[_mapping[key]]);
}
// 调用
this.formatDate('2020-06-13', 'YY/MM/DD');

你可能感兴趣的:(小卖部,js)