排序依据日期值,这是刚刚在角JS字符串 [英] OrderBy Date values, which are just strings in Angular JS
问题描述
我想按日期的订单一些数据,虽然日期仅仅是字符串,格式为DD-MM-YYYY。
I'm trying to order some data by date, although the dates are just strings, in the format dd-mm-yyyy.
我做了一个过滤器,转换成数字的普通字符串(其中美国的日期格式,在这里我想英国的日期格式),如01272012至27-01-2014,但是当我尝试将它们仍只订购看到他们作为数字串,因此1990年1月1日会来2014年2月1日之前。
I made a filter which converted the plain string of numbers (which where in the US date format, where I wanted the UK date format) e.g 01272012 to 27-01-2014, but when I try to order them it still only sees them as numeric strings, so 01-01-1990 would come before 02-01-2014.
如何做到这一点的过滤器有什么建议?
Any suggestions of how to do this in a filter?
谢谢!
更新
我想通了日期将自动获得orderedif日期格式是YYYY-MM-DD。然后我用用排序依据:['日期']
来对数据进行排序,显示数据时,只能用我原来的过滤器
I figured out the dates would automatically get orderedif the date format was yyyy-mm-dd. I then used used orderBy:['date']
to order the data, only using my original filter when displaying the data.
我最后不得不推翻我的数据,显示最近的日期。要做到这一点我添加了一个 -
我的排序依据说明书:排序依据:[' - 日期']
I ended up having to reverse my data, showing the most recent dates. To achieve this I added a -
to my orderBy statment: orderBy:['-date']
.
推荐答案
由于排序依据
过滤器,你可以使用它。
您的NG-repear可能会类似于此:
Because orderBy
filter, you can use that.
Your ng-repear would probably look similar to this:
ng-repeat="item in items | orderBy: orderByDate"
然后您的控制器上,你会定义 orderByDate
功能:
$scope.orderByDate = function(item) {
var parts = item.dateString.split('-');
var date = new Date(parseInt(parts[2],
parseInt(parts[1]),
parseInt(parts[0]));
return date;
};
实现的功能是由你。我选择创建日期
从字符串。您从 orderByDate
然后用函数返回的对象是为了用&LT,=,>运算符。
Implementation of the function is up to you. I choose to create Date
from the string. The object you return from orderByDate
function is then used to be order with using <, =, > operators.
编辑:作为解决方案:反转
由于:反转
不能与作为参数传递的函数中使用,可以实现您的自定义函数返回逆转值本身。在使用日期
这种情况是不可能的,我会构建一个号码,然后,用减号返回它:
Since :reverse
can't be used with a function passed as parameter, you can implement your custom function to return reversed value itself. In such case using Date
is not possible, I would construct a number then and returned it with minus:
$scope.orderByDate = function(item) {
var parts = item.dateString.split('-');
var number = parseInt(parts[2] + parts[1] + parts[0]);
return -number;
};
这篇关于排序依据日期值,这是刚刚在角JS字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!