排序日期不返回排序日期 [英] Sorting Dates Does Not Return Sorted Dates

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

问题描述

出于某种奇怪的原因,我编写的以下函数无法将日期字符串数组转换为javascript日期对象,对其进行排序,然后返回已排序的日期字符串数组无法正确排序:

For some strange reason the following function I wrote for converting an array of date strings to javascript date objects, sorting them, then returning an array of sorted date strings does not sort properly:

sortdates: function(dates, separator) {
    var sorteddates = [],
        datestr =[];
    sorteddates = dates.map(function(val) {
        return new Date(val.replace("/"+separator+"/g", " "));
    }).sort();
    for ( i=0; i<sorteddates.length; i++ ) {
        datestr.push((sorteddates[i].getMonth()+1) + "-" + sorteddates[i].getDate() + "-" + sorteddates[i].getFullYear());
    }
    return datestr;
}

如果我对日期字符串进行测试数组并应用此功能:

If I make a test array of date strings and apply this function:

var testarray = ["2013-8-1", "2013-8-8", "2013-8-15", "2013-8-22", "2013-9-5", "2013-9-12", "2013-8-2", "2013-8-3", "2013-8-4", "2013-8-7", "2013-8-11", "2013-8-14", "2013-8-18", "2013-8-25"];
console.log(sortdates(testarray, "-"));

我将以下内容记录到控制台:

I get the following logged to the console:

["8-2-2013", "8-3-2013", "8-4-2013", "8-11-2013", "8-18-2013", "8-25-2013", "8-1-2013", "8-8-2013", "8-15-2013", "8-22-2013", "9-5-2013", "9-12-2013", "8-7-2013", "8-14-2013"]

显然没有排序.

推荐答案

.sort() 将按字典"顺序排序,而不是数字顺序或日期/时间顺序.如果这些值不是字符串,则将获得默认的字符串转换,该日期转换不会为您提供有用的排序依据.

.sort() will sort in "dictionary" order, not numeric or date/time order. If the values aren't strings they'll get a default string conversion which for dates does not give you something useful to sort on.

但是您可以提供一个自定义的排序回调,该回调知道如何对日期进行排序:

But you can supply a custom sort callback that knows how to sort dates:

.sort(function(a,b) { return a.getTime() - b.getTime(); });

演示: http://jsfiddle.net/TUAz9/

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

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