vue时间格式化,使用用filter+js时间格式化函数

前言:在使用vue做日常做项目中,我们经常会遇见一些时间格式化的需求。如果不写filter的话,甚至连个好用的时间格式化函数都没有的话,每次写一遍十分麻烦,也十分容易出错,所以我今天就把我项目中常用的一些时间格式化函数分享给大家,如果有没有写过filter的同学也可以参考一下,毕竟写代码很重要的一点是能复用嘛!

 

先分享一个比较常用的时间格式化函数

//日期格式化函数
//oDate(时间戳或字符串日期都支持)
//fmt(格式匹配)
//月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
//年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
/*
    例子:
    dateFormat0(new Date(),'yyyy-MM-dd hh:mm:ss.S'); //2018-12-21 17:24:33.664
    dateFormat0(new Date(),'y-M-d h:m:s.S/q'); //2018-12-21 17:24:33.666/4
*/
function dateFormat0(oDate, fmt) {
    //正常化日期
    function normalDate(oDate) {
        var oDate = oDate;
        var reg = /\-+/g;

        if (typeof (oDate) == 'string') {
            oDate = oDate.split('.')[0]; //解决ie浏览器对yyyy-MM-dd HH:mm:ss.S格式的不兼容
            oDate = oDate.replace(reg, '/'); //解决苹果浏览器对yyyy-MM-dd格式的不兼容性
        }

        oDate = new Date(oDate);
        return oDate;
    }
    //时间变成两位数
    function toTwo(n) {
        return +n < 10 ? '0' + n : n + '';
    }

    var fmt = fmt || 'yyyy-MM-dd hh:mm:ss';
    var oDate = normalDate(oDate || new Date()); //不传会默认为当前时间
    var date = {
        'y+': oDate.getFullYear(), //年
        'M+': oDate.getMonth() + 1, //月
        'd+': oDate.getDate(), //日
        'h+': oDate.getHours(), //时
        'm+': oDate.getMinutes(), //分
        's+': oDate.getSeconds(), //秒
        'S': oDate.getMilliseconds(), //毫秒
        'q+': Math.ceil((oDate.getMonth() + 1) / 3), //季度
    };
    var result = '';
    var value = '';

    for (var attr in date) {
        if (new RegExp('(' + attr + ')').test(fmt)) {
            result = RegExp.$1;
            value = date[attr] + '';
            fmt = fmt.replace(result, result.length == 1 ? value : (attr == 'y+' ? value.substring(4 - result.length) : toTwo(value)));
        }
    }
    return fmt;
}

这个函数主要是用于你想格式化时间到具体的年月日或者时分秒,例如:2018-12-21、2018-12-21 17:24:33,还有2018年12月21日。

 

 

如果你接到需求,需要做一个倒计时,但是显示的时间是这样的01年01月01日 01时01分01秒或者25:01:01,那么可以用下面这个函数来实现

//时间格式化函数(根据秒数来格式化)
//seconds(多少秒)
//fmt(格式匹配)
//adjustFmt(是否自动调整格式,会删除无效的格式)
//年(y)、月(M)、日(d)、小时(h)、分(m)、秒(s),都可以用1到任意位占位符
/*
    例子:
    secondFormat0(86400*365+86400*30+86400+3600+60+1,'yy年MM月dd日 hh时mm分ss秒'); //01年01月01日 01时01分01秒
    secondFormat0(86400+3600+60+1,'hh:mm:ss'); //25:01:01
*/
function secondFormat0(seconds, fmt, adjustFmt) {
    //补零函数
    //value(需要补零的值)
    //length(需要补零的长度(数量))
    //isBehind(是否在末尾补零)
    function zeroFill(value, length, isBehind) {
        var value = value || '';
        var length = length > 0 ? length : 0;
        var zeroStr = '';

        for (var i = 0; i < length; i++) {
            zeroStr += '0';
        }

        return !isBehind ? zeroStr + value : value + zeroStr;
    }

    var fmt = fmt || 'yy/MM/dd hh:mm:ss';
    var aMinute = 60;
    var aHour = aMinute * 60;
    var aDay = aHour * 24;
    var aMonth = aDay * 30;
    var aYear = aDay * 365;

    var iYears = Math.floor(seconds / aYear);
    var dMonth = seconds - iYears * aYear > 0 ? seconds - iYears * aYear : 0;
    dMonth = ~fmt.indexOf('y') ? dMonth : seconds;
    var iMonths = Math.floor(dMonth / aMonth);
    var dDay = dMonth - iMonths * aMonth > 0 ? dMonth - iMonths * aMonth : 0;
    dDay = ~fmt.indexOf('M') ? dDay : seconds;
    var iDays = Math.floor(dDay / aDay);
    var dHour = dDay - iDays * aDay > 0 ? dDay - iDays * aDay : 0;
    dHour = ~fmt.indexOf('d') ? dHour : seconds;
    var iHours = Math.floor(dHour / aHour);
    var dMinutes = dHour - iHours * aHour > 0 ? dHour - iHours * aHour : 0;
    dMinutes = ~fmt.indexOf('h') ? dMinutes : seconds;
    var iMinutes = Math.floor(dMinutes / aMinute);
    var dSeconds = dMinutes - iMinutes * aMinute ? dMinutes - iMinutes * aMinute : 0;
    dSeconds = ~fmt.indexOf('m') ? dSeconds : seconds;
    var iSeconds = Math.floor(dSeconds);

    var time = {
        'y+': iYears,
        'M+': iMonths,
        'd+': iDays,
        'h+': iHours,
        'm+': iMinutes,
        's+': iSeconds,
    };
    var result = '';
    var value = '';

    for (var attr in time) {
        if (new RegExp('(' + attr + ')').test(fmt)) {
            result = RegExp.$1;
            value = time[attr] + '';
            value = result.length == 1 ? value : zeroFill(value, result.length - value.length);

            if (adjustFmt && (+value) === 0) {
                var reg = new RegExp(attr + '([^a-zA-Z]+)[a-zA-Z]+');
                var matchStr = fmt.match(reg);

                if (matchStr) {
                    fmt = fmt.replace(matchStr[1], '');
                    value = '';
                }
            }

            fmt = fmt.replace(result, value);
        }
    }
    return fmt;
}

如果你们的产品比较难搞,会提出,需要把时间显示到几分钟前,或者几天前,几个月前这样的需求,那么下面这个函数可以满足

//时间格式化(主要用于格式化历史时间到当前时间是多少秒到多少年前)
//oDate(时间戳或字符串日期都支持)
/*
    dateFormat1(new Date()-3600*1000)//1小时前
*/
function dateFormat1(oDate) {
    //正常化日期
    function normalDate(oDate) {
        var oDate = oDate;
        var reg = /\-+/g;

        if (typeof (oDate) == 'string') {
            oDate = oDate.split('.')[0]; //解决ie浏览器对yyyy-MM-dd HH:mm:ss.S格式的不兼容
            oDate = oDate.replace(reg, '/'); //解决苹果浏览器对yyyy-MM-dd格式的不兼容性
        }

        oDate = new Date(oDate);
        return oDate;
    }

    var oDate = normalDate(oDate);

    if (+oDate >= +new Date()) {
        return '刚刚';
    }
    var lookTime = +new Date() - (+oDate);
    var seconds = Math.floor(lookTime / (1000));
    var minutes = Math.floor(lookTime / (1000 * 60));
    var hours = Math.floor(lookTime / (1000 * 60 * 60));
    var days = Math.floor(lookTime / (1000 * 60 * 60 * 24));
    var months = Math.floor(lookTime / (1000 * 60 * 60 * 24 * 30));
    var years = Math.floor(lookTime / (1000 * 60 * 60 * 24 * 30 * 12));

    if (seconds < 60) {
        lookTime = seconds + '秒前';
    } else if (minutes < 60) {
        lookTime = minutes + '分钟前';
    } else if (hours < 24) {
        lookTime = hours + '小时前';
    } else if (days < 30) {
        lookTime = days + '天前';
    } else if (months < 12) {
        lookTime = months + '个月前';
    } else {
        lookTime = years + '年前';
    }
    return lookTime;
}

 

最后,我来说说怎么在vue中使用filter更方便的来实现格式化

1、首先你需要写一个filter.js,里面把函数引入过来,做一些改造

 

2、在main.js里面引入并挂载过滤器

 

3、最后,你就可以在vue项目中方便的格式化了

{{'2020/6/11 17:46'|date('yyyy-MM-dd')}} // 2020-6-11

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值