日期格式化深拷贝等常用js函数

655 阅读1分钟

日期格式化函数

调用示例 var time1 = new Date().Format("yyyy-MM-dd"); 2017-12-20 var time2 = new Date().Format("yyyy-MM-dd hh:mm:ss"); 2017-12-30 10:10:10 var time3 = new Date('2017-01-09 12:30').Format("yyyyMMddhhmm"); 201701091230


Date.prototype.Format = function(fmt) {
    var o = {
        'M+': this.getMonth() + 1, // 月份
        'd+': this.getDate(), // 日
        'h+': this.getHours(), // 小时
        'm+': this.getMinutes(), // 分
        's+': this.getSeconds(), // 秒
        'q+': Math.floor((this.getMonth() + 3) / 3), // 季度
        'S': this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
    for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
    }
    return fmt;
};

对象深拷贝

  // 对象深拷贝
    deepClone(source) {
        var that = this;
        if (!source && typeof source !== 'object') {
            throw new Error('error arguments', 'shallowClone');
        }
        const targetObj = source.constructor === Array ? [] : {};
        Object.keys(source).forEach((keys) => {
            if (source[keys] && typeof source[keys] === 'object') {
                targetObj[keys] = source[keys].constructor === Array ? [] : {};
                targetObj[keys] = that.deepClone(source[keys]);
            } else {
                targetObj[keys] = source[keys];
            }
        });
        return targetObj;
    },