I am using moment.js
in angularjs application for date conversion. i want to print Month number
as a Month name
. I have tried as bellow,
<p>{{item.ReviewMonth | date : 'MMMM'}}</p>
where item.ReviewMonth
in number formate.
ex-1. <p>{{5 | date : 'MMMM'}}</p>
where 5
is indicate 'May'
but its print january
instead of May
.
ex-2. <p>{{4 | date : 'MMMM'}}</p>
where 4
is indicate 'April'
but its print january
instead of April
.
How can i get correct month name from month number?
To get month name from two digit month number with JavaScript, we can use the moment. js' format method. We call format with 'MMMM' to get the full month name. As a result, formattedMonth is 'October' since we called month with 9 before calling format .
The moment(). daysInMonth() function is used to get the number of days in month of a particular month in Node.
The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().
If you want to use momentjs methods inside your angular view you can use angular-moment.
In your case, you amParse
filter to specify that your input should be interpreted as month number and then you can use amDateFormat
to choose how to display the parsed date.
Here a working sample:
angular.module('MyApp',['angularMoment'])
.controller('AppCtrl', function($scope) {
$scope.item = {};
$scope.item.ReviewMonth = 5;
});
<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.18.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">
<p>{{item.ReviewMonth | amParse:'M' | amDateFormat:'MMMM'}}</p>
</div>
This is because when date
filter trying to convert 5
to Date
object, 5
will be recognized as milliseconds and will be converted to 1970-01-01T00:00:00.005Z
. Then date
filter will return January
.
Solution:
moment('5', 'M').format('MMMM');
or
moment('05', 'MM').format('MMMM');
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.testDate = 5;
$scope.testDate2 = new Date(5);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
<span>{{testDate | date: 'MMMM'}}</span><br>
{{testDate2}}
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With