使用js计算经过了多长时间

使用js计算经过了多长时间

八月 17, 2018 阅读 173 字数 1525 评论 0 喜欢 0

[TOC]
因为要做一个小功能,需要计算两个时间戳之间经过了多久,特此记录一下。

function getTimeAgo(period) {
        var yearLevelValue = 365 * 24 * 60 * 60 * 1000;
        var monthLevelValue = 30 * 24 * 60 * 60 * 1000;
        var dayLevelValue = 24 * 60 * 60 * 1000;
        var hourLevelValue = 60 * 60 * 1000;
        var minuteLevelValue = 60 * 1000;
        var secondLevelValue = 1000;

        function getDifference(period) {
            var year = parseInt(getYear(period));
            var month = parseInt(getMonth(period - year * yearLevelValue));
            var day = parseInt(getDay(period - year * yearLevelValue - month * monthLevelValue));
            var hour = parseInt(getHour(period - year * yearLevelValue - month * monthLevelValue - day * dayLevelValue));
            var minute = parseInt(getMinute(period - year * yearLevelValue - month * monthLevelValue - day * dayLevelValue - hour * hourLevelValue));
            var second = parseInt(getSecond(period - year * yearLevelValue - month * monthLevelValue - day * dayLevelValue - hour * hourLevelValue - minute * minuteLevelValue));
            var result = "";
            if (year != 0) result = result + year + "年";
            if (month != 0) result = result + month + "月";
            if (day != 0) result = result + day + "天";
            if (hour != 0) result = result + hour + "时";
            if (minute != 0) result = result + minute + "分";
            if (second != 0) result = result + second + "秒";

            function getYear(period) {
                return Math.floor(parseInt(period) / yearLevelValue);
            }

            function getMonth(period) {
                return Math.floor(parseInt(period) / monthLevelValue);
            }

            function getDay(period) {
                return Math.floor(parseInt(period) / dayLevelValue);
            }

            function getHour(period) {
                return Math.floor(parseInt(period) / hourLevelValue);
            }

            function getMinute(period) {
                return Math.floor(parseInt(period) / minuteLevelValue);
            }

            function getSecond(period) {
                return Math.floor(parseInt(period) / secondLevelValue);
            }

            return result;
        }

        return getDifference(period);
    }
  • Home
  • code
  • 使用js计算经过了多长时间

发表评论

电子邮件地址不会被公开。