【问题标题】:AngularJS get formatted date in ng-modelAngularJS 在 ng-model 中获取格式化日期
【发布时间】:2014-12-16 16:15:57
【问题描述】:

我在时间戳中有以下由模型值填充的文本输入:

<input type="datetime" ng-model="workerDetail.dateOfBirth"  class="form-control" id="date_of_birth" />

它将输入中的值显示为给定的时间戳。

我想将输入中可见的值转换为格式化日期 (YYYY/MM/DD),但在模型中应始终为时间戳。

我尝试过这样做:

{{workerDetail.dateOfBirth | date:'MMM'}}

但没有运气。

感谢您的建议。

【问题讨论】:

    标签: javascript angularjs date


    【解决方案1】:

    你可以试试过滤器

    HTML

    <input type="datetime" ng-model="mydateOfBirth"  class="form-control" id="date_of_birth" />
    

    控制器 JS

    $scope.$watch('mydateOfBirth', function (newValue) {
        $scope.workerDetail.dateOfBirth = $filter('date')(newValue, 'yyyy/MM/dd'); 
    });
    
    $scope.$watch('workerDetail.dateOfBirth', function (newValue) {
        $scope.mydateOfBirth = $filter('date')(newValue, 'yyyy/MM/dd'); 
    });
    

    【讨论】:

    • 事实上,这个答案在更复杂的例子中给我带来了麻烦,所以我选择了 Sergio Toledo 的答案,一切都很好。
    【解决方案2】:

    您还可以像这样指定时区:

    $scope.$watch('workerDetail.dateOfBirth', function (newDate) {
        $scope.workerDetail.dateOfBirth = $filter('date')(newDate, 'HH:mm', 'UTC'); 
    });
    

    【讨论】:

      【解决方案3】:

      尝试此代码仅获取日期 (dd/mm/yyyy)

      html

      <div class="col-lg-3">
      <input type="date" name="dob" class="input-lg form-group" ng-model='dob'>
      </div>
      

      Angularjs

      app.controller('myctrl',function($scope, $http,$window,$filter) {
      $scope.sent=function(){
          $scope.date = $filter("date")($scope.dob, 'dd-MM-yyyy');
          alert($scope.date);
      }})
      

      【讨论】:

        猜你喜欢
        • 2014-08-03
        • 2016-12-01
        • 1970-01-01
        • 2017-12-10
        • 1970-01-01
        • 2016-01-27
        • 1970-01-01
        相关资源
        最近更新 更多