AngularJS将数字转换为日期格式 [英] AngularJS Convert a number to date format
问题描述
我可以提供以下的小片段来解释什么,我试图做的,但遗憾的是不能共享的主要code,因为它是更为复杂。我相信有一个简单的方法来做到这一点,但它是目前逃逸我。
我已被返回的数据(假设现在为了简单一个JSON文件),其具有在数字格式的日期,但不是一个日期字段。格式为数字,但相当于YYYYMMDD(20140513 = 2014年5月13日)。我有时间成为HHMMSS类似的问题。请注意,我也可以在为YYYYMMDDhhmmss得到一个时间戳。我知道每种类型的格式,但要修改的内容,是人类可读的。
我要显示这是5月13日(或其他数据格式)。
<李NG重复=附表日期>
{{Schedule.Date |日期:'中'}}
< /李>
我的控制器:
VAR应用= angular.module('应用',[]);
App.controller(Ctrl键,功能($范围,$ HTTP)
{
$ http.get(数据/ Schedule.json')。成功(功能(数据){
$ scope.Dates =数据;
});
$ scope.OrderBy ='日期';
});
样的JSON
[
{
ID:13,
日期:20140807,
时间:18:30,
公园:4,
家:5,
离开:2
},
{
ID:14,
日期:20140814,
时间:18:30,
公园:3,
家:2,
离开:6
}
]
如果您可以将日期转换为可识别的格式,这将工作得很好。例如,2014年8月7日将转换就好给你的样品code。可以解决这个问题的一些方法
当你从$ http请求回读数据转换日期属性格式为:
App.controller(Ctrl键,功能($范围,$ HTTP){
$ http.get(数据/ Schedule.json')。成功(功能(数据){
$ scope.Dates = Data.Map中(函数(对象){
object.date =<<转换日期和GT;取代;
返回对象;
});
});
});
,或写自己的过滤器中,输入转换上飞:
App.filter('myDateFilter',函数(){
返回功能(输入,格式){
VAR convertedDate =<<将输入>>
返回$过滤器('日期')(convertedDate,格式);
}
});
I can provide a small snippet below to explain what I am trying to do, but unfortunately can not share the main code as it is more complicated. I believe there is an easy way to do this, but it is escaping me at the moment.
I have data being returned (assume a JSON file for now for simplicity) which has a date in a numeric format, but not a date field. The format is numeric, but is equivalent to YYYYMMDD (20140513 = May 13, 2014). I have a similar problem with Time being HHMMSS. Please note, I might also get a timestamp in YYYYMMDDhhmmss. I do know the format of each type, but want to modify the contents to be human readable.
I want to display this as May 13 (or another date format).
<li ng-repeat="Schedule in Dates">
{{Schedule.Date | date:'medium'}}
</li>
My controller:
var App = angular.module('App', []);
App.controller('Ctrl', function ($scope, $http)
{
$http.get('Data/Schedule.json').success(function(data) {
$scope.Dates = data;
});
$scope.OrderBy = 'date';
});
Sample JSON
[
{
"id": 13,
"date": 20140807,
"time": "18:30",
"park": 4,
"Home": 5,
"Away": 2
},
{
"id": 14,
"date": 20140814,
"time": "18:30",
"park": 3,
"Home": 2,
"Away": 6
}
]
If you can convert the date to a recognizable format this will work just fine. For instance, "2014-08-07" will convert just fine given your sample code. You can tackle this problem a number of ways
convert the date properties to this format when you read back the data from the $http request:
App.controller('Ctrl', function ($scope, $http) {
$http.get('Data/Schedule.json').success(function(data) {
$scope.Dates = data.map(function(object) {
object.date = << convert date >>;
return object;
});
});
});
or, write your own filter that converts the input on the fly:
App.filter('myDateFilter', function(){
return function(input, format) {
var convertedDate = << convert input >>
return $filter('date')(convertedDate, format);
}
});
这篇关于AngularJS将数字转换为日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!