一些项目中能用到的的格式化封装(时间,字符串,对象等)

本文介绍了JavaScript中的时间处理函数,包括日期格式化、添加时间范围、获取当前时间和日期范围筛选选项,以及对象深拷贝等实用工具方法。
摘要由CSDN通过智能技术生成

前五个是若依的时间封装,以下有一些时间封装有引用到第一个

// 日期格式化
export function parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
        return null;
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time);
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.\d{3}/gm), '');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000;
        }
        date = new Date(time);
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value];
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value;
        }
        return value || 0;
    });
    return time_str;
}
// 添加日期范围
export function addDateRange(params, dateRange, propName) {
    const search = params;
    search.params = {};
    if (dateRange != null && dateRange !== '') {
        if (typeof (propName) === 'undefined') {
            search['beginTime'] = dateRange[0];
            search['endTime'] = dateRange[1];
        } else {
            search['begin' + propName] = dateRange[0];
            search['end' + propName] = dateRange[1];
        }
    }
    return search;
}
/**
 * 添加开始和结束时间到 params 参数中
 *
 * @param params 参数
 * @param dateRange 时间范围。
 *                大小为 2 的数组,每个时间为 yyyy-MM-dd 格式
 * @param propName 加入的参数名,可以为空
 */
export function addBeginAndEndTime(params, dateRange, propName) {
    // 必须传入参数
    if (!dateRange) {
        return params;
    }
    // 如果未传递 propName 属性,默认为 time
    if (!propName) {
        propName = 'Time';
    } else {
        propName = propName.charAt(0).toUpperCase() + propName.slice(1);
    }
    // 设置参数
    if (dateRange[0]) {
        params['begin' + propName] = dateRange[0] + ' 00:00:00';
    }
    if (dateRange[1]) {
        params['end' + propName] = dateRange[1] + ' 23:59:59';
    }
    return params;
}
/**
 * 获取当前时间
 * @param timeStr 时分秒 字符串 格式为 xx:xx:xx
 */
export function getNowDateTime(timeStr) {
    const now = new Date();
    const year = now.getFullYear(); //得到年份
    const month = (now.getMonth() + 1).toString().padStart(2, '0'); //得到月份
    const day = now.getDate().toString().padStart(2, '0'); //得到日期

    if (timeStr != null) {
        return `${year}-${month}-${day} ${timeStr}`;
    }
    const hours = now.getHours().toString().padStart(2, '0'); // 得到小时;
    const minutes = now.getMinutes().toString().padStart(2, '0'); // 得到分钟;
    const seconds = now.getSeconds().toString().padStart(2, '0'); // 得到秒;
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

时间日期的封装

/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
    if (cellValue == null || cellValue === '') return '';
    const date = new Date(cellValue);
    const year = date.getFullYear();
    const month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
    const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    const hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    const minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    const seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds;
}
/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
    if (('' + time).length === 10) {
        time = parseInt(time) * 1000;
    } else {
        time = +time;
    }
    const d = new Date(time);
    const now = Date.now();

    const diff = (now - d) / 1000;

    if (diff < 30) {
        return '刚刚';
    } else if (diff < 3600) {
        // less 1 hour
        return Math.ceil(diff / 60) + '分钟前';
    } else if (diff < 3600 * 24) {
        return Math.ceil(diff / 3600) + '小时前';
    } else if (diff < 3600 * 24 * 2) {
        return '1天前';
    }
    if (option) {
        return parseTime(time, option);
    } else {
        return d.getMonth() + 1 + '月' + d.getDate() + '日' + d.getHours() + '时' + d.getMinutes() + '分';
    }
}
export const datePickerOptions = {
    shortcuts: [{
        text: '最近一周',
        onClick(picker) {
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            const end = new Date();
            picker.$emit('pick', [beginOfDay(start), endOfDay(end)]);
        }
    }, {
        text: '最近一个月',
        onClick(picker) {
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            const end = new Date();
            picker.$emit('pick', [beginOfDay(start), endOfDay(end)]);
        }
    }, {
        text: '最近三个月',
        onClick(picker) {
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            const end = new Date();
            picker.$emit('pick', [beginOfDay(start), endOfDay(end)]);
        }
    }]
};
export function beginOfDay(date) {
    return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

export function endOfDay(date) {
    return new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59, 999);
}

深拷贝对象

export function deepClone(obj) {
    const _toString = Object.prototype.toString;

    // null, undefined, non-object, function
    if (!obj || typeof obj !== 'object') {
        return obj;
    }

    // DOM Node
    if (obj.nodeType && 'cloneNode' in obj) {
        return obj.cloneNode(true);
    }

    // Date
    if (_toString.call(obj) === '[object Date]') {
        return new Date(obj.getTime());
    }

    // RegExp
    if (_toString.call(obj) === '[object RegExp]') {
        const flags = [];
        if (obj.global) {
            flags.push('g');
        }
        if (obj.multiline) {
            flags.push('m');
        }
        if (obj.ignoreCase) {
            flags.push('i');
        }

        return new RegExp(obj.source, flags.join(''));
    }

    const result = Array.isArray(obj) ? [] : obj.constructor ? new obj.constructor() : {};

    for (const key in obj) {
        result[key] = deepClone(obj[key]);
    }

    return result;
}

字符串

// 首字母大小
export function titleCase(str) {
    return str.replace(/( |^)[a-z]/g, L => L.toUpperCase());
}

// 下划转驼峰
export function camelCase(str) {
    return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase());
}

export function isNumberStr(str) {
    return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str);
}

// -转驼峰
export function toCamelCase(str, upperCaseFirst) {
    str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
        return group1.toUpperCase();
    });

    if (upperCaseFirst && str) {
        str = str.charAt(0).toUpperCase() + str.slice(1);
    }

    return str;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值