我在angularjs应用程序中使用moment.js
进行日期转换。我想将Month number
打印为Month name
。我已经尝试过了,
<p>{{item.ReviewMonth | date : 'MMMM'}}</p>
其中item.ReviewMonth
为数字格式。
前1。 <p>{{5 | date : 'MMMM'}}</p>
其中5
表示'May'
但它的打印january
代替May
。
EX-2。 <p>{{4 | date : 'MMMM'}}</p>
其中4
表示'四月'
但它的打印january
代替April
。
如何从月份编号中获取正确的月份名称?
答案 0 :(得分:4)
这是因为当date
过滤器尝试将5
转换为Date
对象时,5
将被识别为毫秒,并将转换为1970-01-01T00:00:00.005Z
。然后date
过滤器将返回January
。
解决方案:
moment('5', 'M').format('MMMM');
或
moment('05', 'MM').format('MMMM');
angular.module("app", [])
.controller("myCtrl", function($scope) {
$scope.testDate = 5;
$scope.testDate2 = new Date(5);
});
&#13;
<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>
&#13;
答案 1 :(得分:1)
您可以使用简单的javascript:
从月号中获取月份名称var monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
var month_number = 1;
alert("The current month is " + monthNames[parseInt(month_number)+1]);
或者通过使用时刻js,你可以得到它:
var formattedMonth = moment('09', 'MM').format('MMMM'); // September
moment(
'09', // Desired month
'MM' // Tells MomentJs the number is a reference to month
).format('MMMM') // Formats month as name
答案 2 :(得分:0)
请为月份名称制作简单的指令。
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<any ng-repeat="x in item">
<my-dir myindex="x.ReviewMonth"></my-dir>
</any>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope)
{
$scope.item =
[
{
ReviewMonth:"9"
},
{
ReviewMonth:"2"
},
{
ReviewMonth:"3"
},
{
ReviewMonth:"4"
},
{
ReviewMonth:"5"
},
{
ReviewMonth:"6"
},
{
ReviewMonth:"7"
},
{
ReviewMonth:"7"
}
]
});
app.directive('myDir', function ()
{
return {
restrict: 'E',
scope: {
myindex: '='
},
template:'<div>{{myindex}}</div>',
link: function(scope, element, attrs)
{
var months = ["jan","feb","mar","apr","may","june","july","aug","sep","oct","nov","dec"];
scope.myindex = months[scope.myindex];
}
};
})
</script>
</body>
</html>