2015-10-19 200 views
2

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-模型。 {{getDate | date:'yyyy-MM-dd'}}。但我需要ng-model中的'yyyy-MM-dd'格式,而不是使用日期過濾器。我怎麼解決這個問題?

+0

http://stackoverflow.com/questions/22392328/how-to-format-date-in-angularjs –

回答

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日

+0

謝謝大家配合,謝謝!我用角度用戶界面解決了問題:D –

+0

無需調用* toString *,特別是在評估過程中,月份和日期表達式將參數再次轉換爲數字。那麼'mm [1]?mm:「0」+ mm [0]'可以是'mm> 9?mm:「0」+ mm',同一天。或'('0'+ mm).slice(-2)'。 – RobG

0

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:<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"/>

result

感謝您的意見傢伙! ^^

0

使用ng-bind將模型綁定到其他具有或不具有過濾器的HTML元素。

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