首页 > 解决方案 > 在某些月份停止增加和减少月份

问题描述

目前我在一个窗口中显示 6 个月(从 2019 年 11 月到 2019 年 4 月)。用户可以转到上一个/过去 12 个月(直到 2018 年 11 月),并且可以再前进一个月(2019 年 5 月)。用户可以转到前几个月,也可以转到未来几个月,但我需要限制它。

  months: any[] = [];
    date = new Date();   
    month = this.date.getMonth();
    year = this.date.getFullYear()

      ngOnInit() {
          this.getMonths(this.year, this.month);
        }

        getMonths(year:number, month:number) {
        this.months = [];
          for (let i = 0; i < 6; i++) {
            this.months.push(new Date(year, month++));

          }

        }

        getNextData() {
         this.month++;
         this.getMonths(this.year, this.month);
        }

        getPreviousData(){
        this.month--;
       this.getMonths(this.year, this.month);

     }

标签: javascriptangular

解决方案


我认为以下内容可以帮助您。我重写了你的一些函数并引入了一个辅助函数,用于设计以月表示的日期之间的差异。(因此,如果两个日期相隔一年,则此函数将返回 12)。

然后,您可以根据它们之间的差异比较两个日期。

我还添加了两个值,this.currMonth以便this.currYear您可以充分比较它this.monththis.year原始值。这样想,如果要检查 ifthis.month是否大于以前,则无法检查 if,this.month > this.month + 1因为显然this.month不大于自身加一。而且,如果您增加它,您将重新分配该值,并且您将永远无法与this.month比自身大的值进行比较。this.currMonth并且是恒定的,因此当您确定是否增加/减少时this.currYear,它们总是可以作为比较的好项目this.yearthis.month

这些函数还决定了年份应该何时改变。例如,如果您返回一个月(从 1 月到 12 月),则需要将年份从 2019 年更新到 2018 年。此外,如果月份为 0(1 月),则不能递减它,因为您将得到 -1,不能用作日期比较的月份。您需要将日期更改为 11。相反,如果您从 12 月递增到 1 月,则需要将this.year2018 年更改为 2019 年,而不是递增this.month(这将给您 13-不是有效月份),您需要将其赋值为 0。

months: any[] = [];
    date = new Date();
    currMonth = this.date.getMonth();
    month = this.date.getMonth();
    currYear = this.date.getFullYear();
    year = this.date.getFullYear();

      ngOnInit() {
          this.getMonths(this.year, this.month);
        }

        getMonths(year:number, month:number) {
        this.months = [];
          for (let i = 0; i < 6; i++) {
            this.months.push(new Date(year, month++));
          }

        }

        getNextData() {
         var d1 = new Date(this.currYear, this.currMonth)
         var d2 = new Date(this.year , this.month + 1)
         var diff = this.diff_months(d2, d1)
         if (diff <= 1){
           if (this.month === 11){
                 this.month = 0
                 this.year++
           } else {
                 this.month++ 
           }
         }
       }

       getPreviousData(){
          var m = this.month - 1
          var d1 = new Date(this.currYear, this.currMonth)
          if (this.month === 0){
            var d2 = new Date(this.year-1, 11)
          } else {
            var d2 = new Date(this.year, m)
          }
 
          var diff = this.diff_months(d1, d2)
  
          if (diff <= 12){
             if (m < 0){
               this.month = 11
               this.year--
             } else {
               this.month--
             }
         }
      }
      
      diff_months = (dt2, dt1) => {
         var diff =(dt2.getTime() - dt1.getTime()) / 1000;
         diff /= (60 * 60 * 24 * 7 * 4);
         return Math.abs(Math.round(diff));
      }


推荐阅读