Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

推出前几个月

 /*
        year
        month
        */
        function getMonth(year, month) {
            return year * 12 + month
        }
        /*
        month
        */
        function getYearMonth(month) {
            var year=Math.floor(month/12);
            var month=month%12;
            if(month===0){
                year--;
                month=12
            }
            return {
                year:year,
                month:month
            }
        }
        /*
        推出上个月是几年几月
        *例如 当前2020.06
        getTimeByIndex(0) year:2020 month:6
        getTimeByIndex(1) year:2020 month:5
        getTimeByIndex(6) year:2019 month:12
        */
        function getTimeByIndex(index) {
            var NOW = new Date()
            var YEAR = NOW.getFullYear()
            var MONTH = NOW.getMonth()+1
            var currentMonth = getMonth(YEAR, MONTH);
            currentMonth -= index
            return {
                year: getYearMonth(currentMonth).year,
                month: getYearMonth(currentMonth).month
            }
        }

能不能优化一下


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

其实已有轮子,可以不用重复,moment里面有很多对时间处理的。

当前时间:

//显示结果为:"2020-06-11 11:10:12"

moment(new Date()).format('YYYY-MM-DD HH:mm:ss');

获取前一个月的日期:

//显示结果为:"2020-06-11 11:10:52"

moment(new Date()).subtract(1,'months').format('YYYY-MM-DD HH:mm:ss');

获取前10天的日期:

//显示结果为:"2020-06-01 11:11:52"

moment(new Date()).subtract(10,'days').format('YYYY-MM-DD HH:mm:ss');

获取前一年的日期:

//显示结果为:"2019-06-11 11:10:47"

moment(new Date()).subtract(1,'years').format('YYYY-MM-DD HH:mm:ss');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...