如何更改日期格式angularjs 1.x.

时间:2017-07-25 05:31:56

标签: javascript angularjs

如何在angularjs中将1-Jan-2018更改为1-1-2018

使用HTML模板绑定,如

{{ date_expression | date : format : timezone}}

3 个答案:

答案 0 :(得分:1)

var app = angular.module('app', []);

//app.directive('appDirective', function() {});
//app.factory('appService', function() {});

function AppCtrl($scope) {
  $scope.date_expression = '1-Jan-2018';
}

app.filter('DateFormat',function(){
return function(inputDate, format) {
	var date= new Date(inputDate);
	var addZero=function(number){
		if(number<10){
			return "0"+number;
		}
		else{
			return number;
		}
	}
	var month=addZero(date.getMonth()+1);
	format=format.replace("mm",month);
	var day=addZero(date.getDate());
	format=format.replace("dd",day);
	var year=date.getFullYear();
	format=format.replace("yyyy",year);
	return format;
}
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="AppCtrl">
    <span>
      {{ date_expression | DateFormat:'dd-mm-yyyy'}}
    </span>
  </div>
</div>

答案 1 :(得分:0)

如果我理解正确,这将有助于你

&#13;
&#13;
var app = angular.module('app', []);

//app.directive('appDirective', function() {});
//app.factory('appService', function() {});

function AppCtrl($scope) {
  $scope.date_expression = '1-Jan-2018';
}

app.filter('myFilter', function() {

  // In the return function, we must pass in a single parameter which will be the data we will work on.
  // We have the ability to support multiple other parameters that can be passed into the filter optionally
  return function(input) {

    var output = input.split('-');
    var monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    // Do filter work here
    output[1] = monthNames.indexOf(output[1]) + 1
    return output.join('-');

  }

});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="AppCtrl">
    <span>
      {{ date_expression | myFilter}}
    </span>
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

//add this filter 
app.filter('datetime', function ($filter) {
   return function (input) {
       if (input == null) { return ""; }
       var _date = $filter('date')(new Date(input), 'dd/MM/yyyy'); //You can pass here any date Format whatever you required
       return _date.toUpperCase();
   };
});

//html
<span>{{yourModelValueOfDate | datetime}}</span>