1. 程式人生 > >JS根據搜尋日期往前推12個月

JS根據搜尋日期往前推12個月

mathDate(search){
                console.log(search,"時間");
                var date = new Date(),
                    m = '';
                if(search.month === 0 && search.year.getFullYear() === date.getFullYear()){
                    this.result = [];
                    if(date.getMonth() === 0){
                        for(var j=0;j<12;j++){
                            m = (date.getFullYear()-1)+'-'+(12-j);
                            this.result.push(m);
                        }
                    }else{
                        for (var i=0;i<date.getMonth()+1;i++){
                            m = date.getFullYear()+'-'+(date.getMonth()+1-i);
                            this.result.push(m);
                        }
                        if(this.result.length != 12){
                            for(var j=0;j<12;j++){
                                m = (date.getFullYear()-1)+'-'+(12-j);
                                this.result.push(m);
                            }
                        }
                    }
                    console.log(this.result,"自動日期");
                    this.myChartTrend.setOption({
                        xAxis:[{data:this.result.slice(0,12).reverse()}]
                    });
                }else if(search.month === 0 && search.year.getFullYear() !== date.getFullYear()){
                    this.result = [];
                    for(var k=0;k<12;k++){
                        m = (search.year.getFullYear())+'-'+(12-k);
                        this.result.push(m)
                    }
                    console.log(this.result,"未輸入月份的日期");
                    this.myChartTrend.setOption({
                        xAxis:[{data:this.result.slice(0,12).reverse()}]
                    });
                }else {
                    this.result = [];
                    for (var i=0;i<Number(search.month);i++){
                        m = search.year.getFullYear()+'-'+(Number(search.month)-i);
                        this.result.push(m);
                    }
                    if(this.result.length != 12){
                        for(var j=0;j<12;j++){
                            m = (search.year.getFullYear()-1)+'-'+(12-j);
                            this.result.push(m);
                        }
                    }
                    console.log(this.result,"年月都有的日期");
                    this.myChartTrend.setOption({
                        xAxis:[{data:this.result.slice(0,12).reverse()}]
                    });
                }
            },

     配合echart趨勢柱狀圖使用