在Javascript排序日期 [英] Sort date in Javascript

查看:106
本文介绍了在Javascript排序日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从阿贾克斯查询检索新闻源。在此目的,这种格式的日期:

 周三,2013 08:00:00 GMT 5月22日
 

我想按日期的所有对象进行排序。是否有可能使用JavaScript来做到这一点?

更新

使用这块$ C $了C正常工作!

 中的Array.sort(功能(A,B){
变种C =新的日期(a.date);
变种D =新的日期(b.date);
返回C-D;
});
 

解决方案

1)你不能排序的对象。对象的键的顺序是任意的。

2)如果你想数组排序按日期(和他们已经约会obects),请执行以下操作:

 中的Array.sort(功能(DATE1,DATE2){
     返回DATE1  -  DATE2
});
 

如果您首先需要将其转换为Date对象,请执行下列操作(以下根据下面您的评论中的数据结构):

 中的Array.sort(功能(A,B){
       返回新的日期(a.pubDate) - 新的日期(b.pubDate);
});
 

I have retrieve from ajax query a news feed. In this object, there is a date in this format :

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 ?

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

解决方案

1) You can't sort objects. The order of the object's keys is arbitrary.

2) If you want to sort an array by date (and they are already date obects), do the following:

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

Example

这篇关于在Javascript排序日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆