如何使用 AngularJS 日期过滤器显示时间
How to show time with AngularJS date filter
我想将我的时间显示为上午和下午,可以使用 angular 日期过滤器吗?我试过下面的代码,但对我不起作用。
<div>{{ '12:31:07' | date:'HH:mm' }}</div>
试试自定义过滤器:
HTML:
<div ng-app>
<div ng-controller="TodoCtrl">
<div>{{ '12:31:07' | time }}</div>
</div>
</div>
JS:
angular.module('myApp').filter('time', ['$filter', function ($filter) {
return function (input, arg) {
var parts = input.split(':');
var date = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
return $filter('date')(date, arg || 'mediumTime');
};
}]);
演示:http://jsfiddle.net/U3pVM/33868/
或使用默认过滤器:
尝试:
<div>{{ '12:31:07' | date:'mediumTime' }}</div>
或
<div>{{ '12:31:07' | date:'shortTime' }}</div>
您也可以尝试 'medium'
或 'short'
日期过滤器
根据 Angular 日期过滤器文档,日期参数应采用有效格式。
Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.
因此,您需要事先格式化您的时间字符串。例如;
<div>{{ '2017-09-04T12:31:07' | date:'h:mma' }}</div>
会给你所需的结果。
我想将我的时间显示为上午和下午,可以使用 angular 日期过滤器吗?我试过下面的代码,但对我不起作用。
<div>{{ '12:31:07' | date:'HH:mm' }}</div>
试试自定义过滤器:
HTML:
<div ng-app>
<div ng-controller="TodoCtrl">
<div>{{ '12:31:07' | time }}</div>
</div>
</div>
JS:
angular.module('myApp').filter('time', ['$filter', function ($filter) {
return function (input, arg) {
var parts = input.split(':');
var date = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
return $filter('date')(date, arg || 'mediumTime');
};
}]);
演示:http://jsfiddle.net/U3pVM/33868/
或使用默认过滤器:
尝试:
<div>{{ '12:31:07' | date:'mediumTime' }}</div>
或
<div>{{ '12:31:07' | date:'shortTime' }}</div>
您也可以尝试 'medium'
或 'short'
日期过滤器
根据 Angular 日期过滤器文档,日期参数应采用有效格式。
Date to format either as Date object, milliseconds (string or number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is specified in the string input, the time is considered to be in the local timezone.
因此,您需要事先格式化您的时间字符串。例如;
<div>{{ '2017-09-04T12:31:07' | date:'h:mma' }}</div>
会给你所需的结果。