ajax 在 Javascript 中对日期进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16690035/
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
Sort date in Javascript
提问by pxrb66
I have retrieve from ajax query a news feed. In this object, there is a date in this format :
我从 ajax 查询中检索了一个新闻提要。在这个对象中,有一个这种格式的日期:
Wed, 22 May 2013 08:00:00 GMT
I would like to sort all objects by date. Is it possible to do this using Javascript ?
我想按日期对所有对象进行排序。是否可以使用 Javascript 来做到这一点?
UPDATE
更新
Using this piece of code it works fine !
使用这段代码它工作正常!
array.sort(function(a,b){
var c = new Date(a.date);
var d = new Date(b.date);
return c-d;
});
回答by Christoph
1) You can't sort objects. The order of the object's keys is arbitrary.
1) 您不能对对象进行排序。对象键的顺序是任意的。
2) If you want to sort an array by date (and they are already date obects), do the following:
2) 如果要按日期对数组进行排序(并且它们已经是日期对象),请执行以下操作:
array.sort ( function (date1, date2){
return date1 - date2
});
If you first need to convert them to date objects, do the following (following the data structure according to your comment below):
如果您首先需要将它们转换为日期对象,请执行以下操作(根据您下面的评论遵循数据结构):
array.sort ( function (a, b){
return new Date(a.pubDate) - new Date(b.pubDate);
});
回答by Woppi
You may also use a underscore/lodash sortBy
你也可以使用下划线/lodash sortBy
Here's using underscore js to sort date:
这里使用下划线 js 对日期进行排序:
var log = [{date: '2016-01-16T05:23:38+00:00', other: 'sample'},
{date: '2016-01-13T05:23:38+00:00',other: 'sample'},
{date: '2016-01-15T11:23:38+00:00', other: 'sample'}];
console.log(_.sortBy(log, 'date'));
回答by Kapil gopinath
sorting dates ascending or descending
times = ["01-09-2013", "01-09-2013", "27-08-2013", "27-08-2013", "28-08-2013", "28-08-2013", "28-08-2013", "28-08-2013", "29-08-2013", "29-08-2013", "30-08-2013", "30-08-2013", "31-08-2013", "31-08-2013"]
function dmyOrdA(a,b){ return myDate(a) - myDate(b);}
function dmyOrdD(a,b){ return myDate(b) - myDate(a);}
function myDate(s){var a=s.split(/-|\//); return new Date(a[2],a[1]-1,a[0]);}
times.sort(dmyOrdA);
console.log(times)

