AngularUI日期选择器将变量传递给minDate和maxDate

AngularUI Datepicker passing variables to minDate and maxDate

本文关键字:minDate maxDate 日期 选择器 变量 AngularUI      更新时间:2023-09-26

我想将Angular UI日期选择器限制在作为变量传入的两个日期之间。以下是这个问题的一个有效答案:http://plnkr.co/edit/zsjpoVZtHqJLIP2RW6vm?p=preview

以下是变量:

mycurrentdate = '2016-04-15'
mymindate = '2016-04-01'
mymaxmonth = '2016-05-01'

我的实际最长日期将是mymaxmonth结束,因此在这种情况下:"2016-05-31"

$scope.maxDate = new Date(
                    $scope.mymaxmonth + (TO THE END OF THE MONTH)
                );

需要注意的一点是,通过new Date()运行它会返回给定日期前一天的日期。例如:

$scope.minDate = new Date(
                    $scope.mymindate
                );

其中$scope.minDate返回Wed Mar 30 2016 17:00:00 GMT-0700 (PDT)我查找了它返回3月30日而不是4月1日的原因,这似乎是一个时区错误?

我想将mymindate设置为"2016-04-01",并获取mymaxdate='2016-05-31'并禁用此范围之外的所有日期。我特别不想知道如何到月底。javascript中有endofmonth()函数吗?

在控制器中我有:

$scope.mymindate = '2016-04-01';
$scope.mymaxmonth = '2016-05-01'; //want mymaxdate to be '2016-05-31'
$scope.minDate = new Date(
  $scope.mymindate
  );
$scope.maxDate = new Date(
  $scope.mymaxmonth + 1
  );

在模板中我有:

<p class="input-group">
          <input type="text" class="form-control" uib-datepicker-popup="{{format}}" ng-model="dt" is-open="popup1.opened" min="minDate" max="maxDate" datepicker-options="dateOptions" ng-required="true" close-text="Close" alt-input-formats="altInputFormats" />
          <span class="input-group-btn">
            <button type="button" class="btn btn-default" ng-click="open1()"><i class="glyphicon glyphicon-calendar"></i></button>
          </span>
        </p>

Plunkr中的示例不会按照编写方式工作。

我建议您先阅读一些关于如何使用普通Javascript正确操作Javascript日期的文章。

一旦你知道了你想要操作什么以及如何操作(在这种情况下是月),我建议你使用一个可以轻松完成的库,比如MomentJS。

Moment将允许你选择任何日期,并允许你以任何方式操纵它,包括添加、月底和本地(时区固定)。

moment()包装任何日期,可以参考MomentJS文档来做你想做的事情。您仍然需要将日期包装在new Date()中,以便它在Angular UI日期选择器中工作。

new Date(moment($scope.mymaxmonth).add(1,'months')); //Fri Jun 1 2016 16:41:02 GMT-0700 (Pacific Daylight Time)
new Date(moment($scope.mymaxmonth).endOf('month')); // Tue May 31 2016 23:59:59 GMT-0700 (Pacific Daylight Time)
new Date(moment($scope.mymindate).local()); //Fri Apr 01 2016 00:00:00 GMT-0700 (Pacific Daylight Time)

这里有几种方法可以将moment集成到您的Angular应用程序中。