[工具(前端)] 时间处理工具函数

[工具(前端)] 时间处理函数

牛马前端,在项目中避免不了使用到时间,比如格式化日期,时间戳日期,计算活动是否开始结束…等等。所以此文章收集一些常用的时间处理工具函数。后续有新增会继续往里面添加

格式化日期

/**
 * 格式化日期
 * @param date 日期 默认 当前时间
 * @param format 格式 默认 YYYY-MM-DD HH:mm:ss
 * @returns {string}
 */
formatDateTime:(date, format="YYYY-mm-dd HH:MM:SS") => {
    if(!(date instanceof Date)){
        //不是日期类型时进行转化
        date = new Date(date);
        if(date.toString() === 'Invalid Date'){
            return 'date参数类型错误'
        }
    }
    let ret;
    const opt = {
        "Y+": date.getFullYear().toString(), // 年
        "m+": (date.getMonth() + 1).toString(), // 月
        "d+": date.getDate().toString(), // 日
        "H+": date.getHours().toString(), // 时
        "M+": date.getMinutes().toString(), // 分
        "S+": date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加,必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(format);
        if (ret) {
            format = format.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        }
    }
    return format;
}

格式化时间

/**
 * 格式化时间
 * @param seconds 秒数
 * @param format 格式 默认 HH:mm:ss
 * @returns {string}
 */
formatTimeWithPattern:(seconds, format = 'HH:mm:ss')=> {
    let hours = Math.floor(seconds / 3600);
    let minutes = Math.floor((seconds % 3600) / 60);
    let remainingSeconds = seconds % 60;
    // 根据格式字符串替换相应的值
    let formattedTime = format
        .replace('HH', hours < 10 ? '0' + hours : hours)
        .replace('hh', hours % 12 || 12) // 12小时制
        .replace('mm', minutes < 10 ? '0' + minutes : minutes)
        .replace('ss', remainingSeconds < 10 ? '0' + remainingSeconds : remainingSeconds)
        .replace('SSS', Math.floor((remainingSeconds - Math.floor(remainingSeconds)) * 1000));
    return formattedTime;
}

计算两个日期之间的天数

/**
 * 计算两个日期之间的天数
 * @param date1 间隔时间1
 * @param date2 间隔时间2
 * @returns {number}  返回天数
 */
daysBetween(date1, date2) {
    // 获取两个日期的毫秒数
    let timeDiff = Math.abs(date2.getTime() - date1.getTime());
    // 转换为天数
    let diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
    return diffDays;
}

获取当前日期加上指定天数后的日期

/**
 * 获取当前日期加上指定天数后的日期
 * @param days 加的天使
 * @param isFormat 是否格式化
 * @param format 格式
 * @returns {Date | string}
 */
addDaysToDate(days,isFormat=true,format="YYYY-mm-dd") {
    days = parseInt(days);
    let currentDate = new Date();
    currentDate.setDate(currentDate.getDate() + days);
    if(isFormat) return this.formatDateTime(currentDate,format);
    return currentDate;
}

获取当前日期减去指定天数后的日期

/**
 * 获取当前日期减去指定天数后的日期
 * @param days 减的天数
 * @param isFormat 是否格式化
 * @param format 格式
 * @returns {Date | string}
 */
delDaysToDate(days,isFormat=true,format="YYYY-mm-dd") {
    days = parseInt(days);
    let currentDate = new Date();
    currentDate.setDate(currentDate.getDate() - days);
    if(isFormat) return this.formatDateTime(currentDate,format);
    return currentDate;
}

获取给定日期是周几

/**
 * 获取给定日期是周几
 * @param date 日期
 * @returns {string}
 */
getDayOfWeek(date=new Date()) {
    const dayOfWeek = date.getDay();
    let dayName;
    switch (dayOfWeek) {
        case 0:
            dayName = '周日';
            break;
        case 1:
            dayName = '周一';
            break;
        case 2:
            dayName = '周二';
            break;
        case 3:
            dayName = '周三';
            break;
        case 4:
            dayName = '周四';
            break;
        case 5:
            dayName = '周五';
            break;
        case 6:
            dayName = '周六';
            break;
        default:
            dayName = '未知';
    }

    return dayName;
}

获取时间是几天前 几年前 几月前

/**
 * 获取时间是几天前 几年前 几月前
 * @param dateStr
 * @returns {string}
 */
timeDifference:(dateStr)=> {
    let specifiedDate = new Date(dateStr);
    let currentDate = new Date();
    let diffTime = Math.abs(currentDate - specifiedDate);
    let diffDays = diffTime / (1000 * 60 * 60 * 24);
    let diffMonths = (currentDate.getFullYear() - specifiedDate.getFullYear()) * 12 + currentDate.getMonth() - specifiedDate.getMonth();
    let diffYears = currentDate.getFullYear() - specifiedDate.getFullYear();
    if (diffDays < 30) {
        return `${Math.round(diffDays)}天前`;
    } else if (diffMonths < 12) {
        return `${diffMonths}个月前`;
    } else {
        return `${diffYears}年前`;
    }
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值