【问题标题】:Angular js - increment months in $scopeAngular js - 在 $scope 中增加月份
【发布时间】:2014-11-01 11:51:16
【问题描述】:

我想像这样增加月份:

 var date = new Date();
    $scope.month = $filter('date')(date, 'MMMM');
    $scope.nextMonth = function () {                
     //set next month
     $scope.month = $filter('date')(new Date($scope.month).getMonth()+1, 'MMMM');
    };

我怎样才能做到这一点?

例如如果

$scope.month = "November";

$scope.nextMonth(); 应该设置$scope.month = "December";

注意:我不能为此使用任何外部库

【问题讨论】:

    标签: javascript angularjs date filter


    【解决方案1】:

    Angular 没有内置任何东西来执行此操作,因此您需要使用原生 Javascript Date 方法。

    但是,如果您在日期方面做了大量工作,我强烈推荐moment.js

    这将使上面的内容变得非常简单:

    $scope.month = moment().format('MMMM')
    $scope.nextMonth = function(){
        $scope.month.add(1, 'month');
    }
    

    编辑:

    在不使用外部库的情况下,您仍然可以这样做,并且您几乎拥有代码:

    $scope.nextMonth = function(){
      date.setMonth(date.getMonth() + 1);
      return $scope.month = $filter('date')(date, 'MMMM');
    }
    

    【讨论】:

    • 对不起,我忘了说我没有使用 moment.js,我不能使用它:P
    • 不,您是根据当前月份而不是根据 scope.month 设置 +1 个月:P
    • 我需要每次都增加 scope.month 而不是当前月份;)
    • 好吧,您将$scope.month 设置为字符串,因此要么将其转换回基于该日期的日期,然后添加一个月,要么保存字符串($scope.month.name)和日期对象 ($scope.month.date) 并从那里开始工作...
    • 另外,除非您在别处更改$scope.month,否则date $scope.month。这行var date = new Date(); 只运行一次。
    【解决方案2】:

    只工作几个月

    $scope.nextMonth = function(){
      var index = $locale.DATETIME_FORMATS.MONTH.indexOf($scope.month);
      $scope.month = $locale.DATETIME_FORMATS.MONTH[index == 11 ? 0 : index + 1];
    }
    

    【讨论】:

      【解决方案3】:
       $scope.date = (new Date((new Date()).setMonth((new Date()).getMonth()
       + 1))).toLocaleDateString('fr-FR')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多