使用$ scope值使用momentjs比较日期

时间:2017-03-17 01:13:14

标签: angularjs angularjs-scope momentjs

我目前正在使用select选项生成月份和年份,使用角度属性ng-repeat来收集信用卡到期日期的数据。我想在将它们连接成一个字符串之后返回月份和年份的值,并使用momentjs将字符串与今天的日期进行比较。执行此操作时,月份和年份将作为无效日期返回。请参阅下面的示例:

HTML

<select id="expMonth" class="form-control" ng-model="expMonth" ng-change="checkDate()">
   <option value="" disabled>Month</option>
   <option value="{{ month }}" ng-repeat="month in months">{{ month }}</option>
</select>

 <select id="expYear" class="form-control" ng-model="expYear" ng-change="checkDate()">
    <option value="" disabled>Year</option>
    <option value="{{ year }}" ng-repeat="year in years">{{ year }}</option>
 </select>

的Javascript /角

$scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
$scope.years = [];
var currentYear = new Date().getFullYear ();
for ( var i = currentYear; i <= new Date ().getFullYear () + 10; i++ ) $scope.years.push ( i );

$scope.checkDate = function() {
    var expDate = $scope.expMonth.toString() + $scope.expYear.toString();
    if (expDate < moment().format('MMYYYY')) {
      console.log('please enter an invalid date');
    } else {
      console.log('this date is valid')
    }
}

我相信日期会以字符串形式返回,我不知道如何转换它以便我可以使用moment.format('MMYYYY')将其与今天的日期进行比较。任何帮助都是极好的。

1 个答案:

答案 0 :(得分:1)

您正在尝试比较一个字符串是否小于另一个不起作用的字符串。您有两种选择:

  1. 分别比较月份和年份
  2. 使用时刻isBefore方法比较日期
  3. 单独比较:

    $scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
    $scope.years = [];
    var currentMonth = new Date().getMonth();
    var currentYear = new Date().getFullYear();
    for (var i = currentYear; i <= new Date().getFullYear() + 10; i++) $scope.years.push(i);
    
    $scope.checkDate = function() {
      if (!($scope.expMonth && $scope.expYear)) return;
      if ($scope.expMonth <= currentMonth && $scope.expYear <= currentYear) {
        console.log('please enter an valid date');
      } else {
        console.log('this date is valid');
      }
    }
    

    时刻isBefore

    $scope.months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
    $scope.years = [];
    var currentMonth = new Date().getMonth();
    var currentYear = new Date().getFullYear();
    for (var i = currentYear; i <= new Date().getFullYear() + 10; i++) $scope.years.push(i);
    
    $scope.checkDate = function() {
      if (!($scope.expMonth && $scope.expYear)) return;
      var expDate = $scope.expMonth.toString() + $scope.expYear.toString();
      if (moment(expDate, 'MMYYYY').isBefore()) {
        console.log('please enter an valid date');
      } else {
        console.log('this date is valid');
      }
    }