Javascript jQuery 日期排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10636779/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:15:36  来源:igfitidea点击:

jQuery date sorting

javascriptjquerydatetimesorting

提问by Sandeep Kumar

Possible Duplicate:
Javascript date sorting by convert the string in to date format

可能的重复:
通过将字符串转换为日期格式的 Javascript 日期排序

I am not good in jquery so I was wondering if there is a way or plugin I can use to sort date divs. I have date in YYYY:MM:DD HH:MM:SS format. I am displaying date in divs as shown below. Divs are in unordered format and I want to sort them on latest date first basis.

我不擅长 jquery,所以我想知道是否有一种方法或插件可以用来对日期 div 进行排序。我有 YYYY:MM:DD HH:MM:SS 格式的日期。我在 div 中显示日期,如下所示。Div 是无序格式,我想先按最新日期对它们进行排序。

<div id="dateDiv">2012-04-15 10:25:45</div>
<div id="dateDiv">2012-04-10 19:41:08</div>
<div id="dateDiv">2012-04-20 07:00:10</div>
<div id="dateDiv">2012-04-12 16:45:50</div>

Thanks

谢谢

回答by Parth Thakkar

I don't know much about plugins...although if you want a light weight method without plugins, you may try this:

我对插件了解不多……虽然如果你想要一个没有插件的轻量级方法,你可以试试这个:

html:

html:

<div id="D">
    <div class="dateDiv">2012-04-15 10:25:45</div>
    <div class="dateDiv">2012-04-10 19:41:08</div>
    <div class="dateDiv">2012-04-20 07:00:10</div>
    <div class="dateDiv">2012-04-12 16:45:50</div>
</div>

For js:

对于js:

var elems = $.makeArray($(".dateDiv"));
elems.sort(function(a, b) {
    return new Date( $(a).text() ) < new Date( $(b).text() );
});
$("#D").html(elems);

UPDATE:
Thanks to CMS for answering this question about parsing dates: Why does Date.parse give incorrect results?

更新
感谢 CMS 回答有关解析日期的问题:为什么 Date.parse 给出不正确的结果?

function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2], parts[3], parts[4], parts[5]); //     months are 0-based
}

var elems = $.makeArray($(".dateDiv"));
elems.sort(function(a, b) {
    console.log( parseDate( $(a).text() ) );
    return parseDate( $(a).text() ) < parseDate( $(b).text() );
});
$("#D").html(elems);?

Now, don't tell me this doesn't work...hehe

现在,不要告诉我这不起作用...呵呵

回答by PinnyM

You can use the date.jslibrary combined with thissorter function to do this:

您可以使用date.js库与排序器功能相结合来执行此操作:

$('#dateDiv').sortElements(function(a, b){
    return Date.parse($(a).text()) > Date.parse($(b).text()) ? 1 : -1;
});

The original repo has not been maintained, but an updated fork of it appears to be in progress here.

原来的回购尚未被维持,但它的一个更新的叉子似乎正在这里