日期格式化

来源:互联网 发布:螺纹钢理论重量表算法 编辑:程序博客网 时间:2024/06/05 14:37

var  format  = 'yyyy-mm-dd:hh:mm:ss'

function formatDate (source,  format ) {
    let date = new Date();
    if (typeof source === 'string') format = source;
    if (typeof source === 'number') date = new Date(source);
    if (typeof source === 'object') date = source;


    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const miniute = date.getMinutes();
    const second = date.getSeconds();
    return format.replace('yyyy', year)
                  .replace('MM', month)
                  .replace('dd', day)
                  .replace('hh', hour)
                  .replace('mm', miniute)
                  .replace('ss', second)
                  .replace(/\b\d{1}\b/g, '0$&');
}