【问题标题】:How to change input date format?如何更改输入日期格式?
【发布时间】:2015-10-19 09:29:18
【问题描述】:

JS:

$scope.getDate = new Date();

HTML:

<div class="col-sm-4">
   <input type="date" ng-model="getDate" class="form-control input-sm">
</div>

结果:10/19/2015(在 Chrome 中)

不使用 ng-model 很容易。 {{getDate | date:'yyyy-MM-dd'}}。但我需要 ng-model 中的 'yyyy-MM-dd' 格式,而不是使用日期过滤器。我该如何解决这个问题?

【问题讨论】:

标签: javascript angularjs date input


【解决方案1】:

你可以试试这样的:

Date.prototype.myformat = function() {
        var yyyy = this.getFullYear().toString();
        var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
        var dd  = this.getDate().toString();
        return yyyy + "-" + (mm[1]?mm:"0"+mm[0]) + "-" + (dd[1]?dd:"0"+dd[0]); // padding
      };
var dd = new Date();
$scope.getDate = dd.myformat;

结果:2015-10-19

【讨论】:

  • 谢谢哥们,谢谢!我用 Angular UI 解决了这个问题:D
  • 不需要调用 toString,尤其是当月和日表达式在计算期间再次将参数转换回数字时。那么mm[1]?mm:"0"+mm[0] 可以是mm &gt; 9?mm:"0"+mm,一天也一样。或('0'+mm).slice(-2).
【解决方案2】:

JS :$scope.open = function($event) { $scope.status.opened = true; }; $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.format = 'yyyy-MM-dd'; var app = angular.module('someApp',['ui.bootstrap']); //app.js

HTML : &lt;input type="text" class="form-control sm" ng-click="open($event)" datepicker-mode="month" datepicker-popup="{{format}}" ng-model="getDate" is-open="status.opened" datepicker-options="dateOptions" ng-required="true" current-text="Today" clear-text="Clear" close-text="Close"/&gt;

感谢你们的 cmets 伙计们! ^^

【讨论】:

    【解决方案3】:

    使用ng-bind 将模型绑定到其他带有或不带有过滤器的 HTML 元素。

    <p ng-bind=" getDate | date:'yyyy-MM-dd'"></p>
    

    【讨论】:

      猜你喜欢
      • 2019-03-28
      • 2019-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 1970-01-01
      • 2018-10-30
      • 1970-01-01
      相关资源
      最近更新 更多