javascript 将日期和时间转换为单一格式字符串的角度过滤器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22985779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
angular filter which convert date and time to single formatted string
提问by Jeetendra Chauhan
I am using data from a API, which returns a date and time in two different key/value pair (date and time).
我正在使用来自 API 的数据,它以两个不同的键/值对(日期和时间)返回日期和时间。
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body ng-controller="ctrl">
Date {{date}} - Time {{time}}
<br/>
{{date | dateformatter}}
</body>
</html>
angular.module("app",[]).controller("ctrl", function($scope) {
$scope.date = "03/13/2014";
$scope.time = "8:10:56";
}).filter("dateformatter", function($filter){
// this should return 'yyyy-MM-dd h:mm:ss'
return function(dt) {
return "2014 03 13 8:10:56";
}
})
Can I use a filter to convert it to a single formatted string?
我可以使用过滤器将其转换为单一格式的字符串吗?
采纳答案by Maxim Shoustin
I would convert Date
and Time
to Date
object and use Date filter
我会转换Date
,并Time
以Date
对象和用途Date filter
So controller looks like:
所以控制器看起来像:
app.controller("ctrl", function($scope) {
$scope.date = "03/13/2014";
$scope.time = "8:10:56";
$scope.newDate = new Date( $scope.date + ' ,' + $scope.time).getTime();
});
and HTML:
和HTML:
{{newDate | date: 'yyyy-MM-dd h:mm:ss'}}
Demo Fiddle
演示 Fiddle
回答by Fabien Gane
An other quick way to do that :
另一种快速的方法是:
angular
.module('PrivateModule')
.controller('MyController', ['$scope', function ($scope) {
$scope.Date = function(date) {
return new Date(date);
}
}
Then in your view :
那么在你看来:
<span>{{Date(obj.start) | date : 'dd/MM/yyyy'}}</span>
回答by srph
Here's an attempt:
这是一个尝试:
+(function(angular, undefined) {
angular
.module('app')
.filter('timestamp', filter);
function filter() {
return function filterFn(input) {
return ( Date.parse(input) );
}
}
})(angular);
Usage: {{ date | timestamp | date: 'MMM d, yyyy' }}
. In your case, {{ date + ' ,' + time | timestamp | date: 'MMM d, yyyy' }}
.
用法:{{ date | timestamp | date: 'MMM d, yyyy' }}
。在你的情况下,{{ date + ' ,' + time | timestamp | date: 'MMM d, yyyy' }}
.
This is a better solution, removing concerns that do notbelong to a controller.
这是一个更好的解决方案,消除了不属于控制器的问题。
Will be making this available to bower soon, check myrepository, if ever that's better than a copy-pasting the gist / snippet(whatever suits the dev).