常用时间处理函数(持续更新中)

常用时间处理函数

一、时间戳转化为时间


      function timestampToTime(timestamp) {

        var date = new Date(timestamp); 

        var Y = date.getFullYear() + '-';

        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';

        var D = date.getDate() + ' ';

        D = D < 10 ? '0' + D : D

        var h = date.getHours();

        h = h < 10 ? '0' + h : h

        var m = date.getMinutes();

        m = m < 10 ? '0' + m : m

        var s = date.getSeconds();

        s = s < 10 ? '0' + s : s

        return Y + M + D + h + ':' + m + ':' + s;

      }

 二、根据时间撮,计算起止时间的时间间隔


      function calculateTimeDifference(timestampB, timestampA) {

        let timeDifference = timestampB - timestampA;

        let leave1 = timeDifference % (24 * 3600 * 1000);

        let days = Math.floor(timeDifference / (24 * 3600 * 1000));

        let hours = Math.floor(leave1 / (3600 * 1000));

        let leave2 = leave1 % (3600 * 1000);

        let minutes = Math.floor(leave2 / (60 * 1000));

        let leave3 = leave2 % (60 * 1000);

        let seconds = Math.round(leave3 / 1000);

        return days + "天" + hours + "小时" + minutes + "分钟" + seconds + "秒";

      }

三、温馨提示

在使用以上函数是,一定要注意事时间戳是几位数的。时间戳为10位需*1000,时间戳为13位不需乘1000; 

四、时间戳转化为时间

(注意:下面的date可以加个判断是10位时间戳还是13位时间戳来进行编码是否需要*1000; param为你要转换的时间戳变量
    if(param.length == 10){
        let date = new Date(parseInt(param) * 1000);
    }else if(param.length == 13){
         let date = new Date(parseInt(param));
    }
 )
发布了110 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Lemontree_fu/article/details/101012004