1. 程式人生 > >js目標時間與當前時間差轉換年月日天數

js目標時間與當前時間差轉換年月日天數

後端同同不肯給我算好的時間差給我,只好自己寫了:

 getdate(4292488)  使用方法傳入目標時間與當前時間差(時間戳)
function getdate(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 + "天";
            result = result + hour + "時" + minute + "分" + second + "秒";
            function getYear(period) {
                return parseInt(period) / yearLevelValue;
            }
            function getMonth(period) {
                return parseInt(period) / monthLevelValue;
            }
            function getDay(period) {
                return parseInt(period) / dayLevelValue;
            }
            function getHour(period) {
                return parseInt(period) / hourLevelValue;
            }
            function getMinute(period) {
                return parseInt(period) / minuteLevelValue;
            }
            function getSecond(period) {
                return parseInt(period) / secondLevelValue;
            }
            return result;
        }
        return getDifference(period);
    }