You can use angular built-in filter for date (as suggested in other answers), if your input is:
- a JavaScript Date object
- a number that represents milliseconds (this can be also a string)
- a string in ISO 8601 format (e.g.
yyyy-MM-ddTHH:mm:ss.sssZ
, yyyy-MM-dd
etc)
Your date
is a string with a format that is not ISO 8601, so you have to change the way you parse 2-1-2017
into a date.
You can parse your string in your controller using moment(String, String)
as shown in the following example:
angular.module('MyApp',['angularMoment'])
.controller('AppCtrl', function($scope) {
$scope.dates = [
// Wrong way to parse string
moment('2-1-2017').toDate(),
// Parse string specifying format
moment('2-1-2017', 'D-M-YYYY').toDate()
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.1/angular-moment.min.js"></script>
<div ng-app="MyApp" ng-controller="AppCtrl">
<div ng-repeat="date in dates">
<span>angular-moment: {{date | amDateFormat:'DD'}}</span>
<span>angular date filter: {{date | date:"dd"}}</span>
</div>
</div>
If you don't want to modify your controller you can use angular moment amParse
filter. As the docs says, this filter:
Parses a custom-formatted date into a moment object that can be used with the am-time-ago
directive and the other filters.
So in your case, you can use the code shown in the following example:
angular.module('MyApp',['angularMoment'])
.controller('AppCtrl', function($scope) {
$scope.dates = [
'2-1-2017', // February 2 2017
'15-1-2017' // January 15 2017
];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.9/angular.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.1/angular-moment.min.js"></script>
<div ng-app="MyApp" ng-controller="AppCtrl">
<div ng-repeat="date in dates">
<span>angular-moment: {{date | amParse:'D-M-YYYY' | amDateFormat:'DD'}}</span>
</div>
</div>
date
variable (date, sting, moment object)? Do you have warning in the console? – Disraeli