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

常用时间处理函数

一、时间戳转化为时间


      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; 

 

 

你可能感兴趣的:(js)