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
}
]
有帮助吗?

解决方案 2

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);
    }
});

其他提示

Unless you're following an ISO8601 format or it's a Date object, you won't be able to use the date filter. My suggestion would be to either change you your data is returned so that it's in the proper format, or write your own filter to parse this for you.

<li ng-repeat="Schedule in Dates">
    {{Schedule.Date | customDate}}
</li>

And the filter:

var App = angular.module('App', []);
App.filter('customDate', function(){
    return function(numericDateTime){
        //TODO: Custom date logic
    }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top