js 获取距离某个时间过去了多少年,天,月,等

	/**
     * 根据指定的t,获取t距离现在过去了多少天
     * @param t     指定的时间
     * @return {any} elapsed 过去的时间
     */
    function     getElapsedTime(t) {

        let now = Date.now();
        let elapsed = now - t
        let result = ''
        let second = 1000;
        let minute = 60 * second;
        let hours = 60 * minute;
        let day = 24 * hours;
        let months = [31,28,31,30,31,30,31,31,30,31,30,31]
        let nowYear = new Date(now).getFullYear()
        let nowMonth = new Date(now).getMonth()
        //判断是不是闰年
        if(nowYear%4===0 && nowYear%100!==0 || nowYear%400===0)months[1]=29;
        let month = Math.abs(new Date(t).getMonth() - nowMonth)
        let year = nowYear - new Date(t).getFullYear()

        if (year !== 0 && month >= 12) result = year + '年'
        else if (month !== 0 &&  Math.round(elapsed / day) >= months[nowMonth]) return month + '个月'
        else if (parse(day) !== 0) result= parse(day) + '天'
        else if (parse(hours) !== 0) result= parse(hours) + '小时'
        else if (parse(minute) !== 0) result = parse(minute) + '分钟'
        else if (parse(second) !== 0) result = parse(second) + '秒'
        else if(parse(1) !== 0)result = parse(1) + '毫秒'
        else result = '0毫秒'

        function parse(time) {
            return  Math.round(elapsed/time)
        }
        return result;
    }
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值