Javascript 对字符串日期数组进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30691066/
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 a string date array
提问by Suyog Sawant
I want to sort an array in ascending order. The dates are in string format
我想按升序对数组进行排序。日期为字符串格式
["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"]
Even need a function to check whether these dates are in continuous form:
甚至需要一个函数来检查这些日期是否为连续形式:
eg - Valid - ["09/06/2015", "10/06/2015", "11/06/2015"]
Invalid - ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015"]
Example code:
示例代码:
function sequentialDates(dates){
var temp_date_array = [];
$.each(dates, function( index, date ) {
//var date_flag = Date.parse(date);
temp_date_array.push(date);
});
console.log(temp_date_array);
var last;
for (var i = 0, l = temp_date_array.length; i < l; i++) {
var cur = new Date();
cur.setTime(temp_date_array[i]);
last = last || cur;
//console.log(last+' '+cur);
if (isNewSequence(cur, last)) {
console.log("Not Sequence");
}
}
//return dates;
}
function isNewSequence(a, b) {
if (a - b > (24 * 60 * 60 * 1000))
return true;
return false;
}
回答by Roberto
The Simple Solution
简单的解决方案
There is no need to convert Strings to Dates or use RegExp.
无需将字符串转换为日期或使用 RegExp。
The simple solution is to use the Array.sort() method. The sort function sets the date format to YYYYMMDD and then compares the string value. Assumes date input is in format DD/MM/YYYY.
简单的解决方案是使用 Array.sort() 方法。sort 函数将日期格式设置为 YYYYMMDD,然后比较字符串值。假设日期输入的格式为 DD/MM/YYYY。
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
// return a.localeCompare(b); // <-- alternative
});
Update:
更新:
A helpful comment suggested using localeCompare()to simplify the sort function. This alternative is shown in the above code snippet.
建议使用一个有用的注释localeCompare()来简化排序功能。这种替代方法显示在上面的代码片段中。
Run Snippet to Test
运行代码段进行测试
<!doctype html>
<html>
<body style="font-family: monospace">
<ol id="stdout"></ol>
<script>
var data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
data.sort(function(a,b) {
a = a.split('/').reverse().join('');
b = b.split('/').reverse().join('');
return a > b ? 1 : a < b ? -1 : 0;
// return a.localeCompare(b); // <-- alternative
});
for(var i=0; i<data.length; i++)
stdout.innerHTML += '<li>' + data[i];
</script>
</body>
</html>
回答by Cristik
You will need to convert your strings to dates, and compare those dates, if you want to sort them. You can make use of the parameter that the sortmethod accepts, in order to achieve this:
如果要对它们进行排序,则需要将字符串转换为日期,并比较这些日期。您可以利用该sort方法接受的参数,以实现此目的:
var dateStrings = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
var sortedStrings = dateStrings.sort(function(a,b) {
var aComps = a.split("/");
var bComps = b.split("/");
var aDate = new Date(aComps[2], aComps[1], aComps[0]);
var bDate = new Date(bComps[2], bComps[1], bComps[0]);
return aDate.getTime() - bDate.getTime();
});
In order to reduce code redundancy, and to handle different date formats, you can add an additional function that will create the comparator needed by the sortmethod:
为了减少代码冗余并处理不同的日期格式,您可以添加一个额外的函数来创建sort方法所需的比较器:
function createSorter(dateParser) {
return function(a, b) {
var aDate = dateParser(a);
var bDate = dateParser(b);
return aDate.getTime() - bDate.getTime();
};
}
dateStrings.sort(createSorter(function(dateString) {
var comps = dateString.split("/");
return new Date(comps[2], comps[1], comps[0]);
}));
You can then use different date formatters by passing different functions to the createSortercall.
然后,您可以通过将不同的函数传递给createSorter调用来使用不同的日期格式化程序。
As for your second question, you can create an (sorted) array of dates from your strings, and perform your logic on that array:
至于你的第二个问题,你可以从你的字符串创建一个(排序的)日期数组,并在该数组上执行你的逻辑:
function myDateParser(dateString) {
var comps = dateString.split("/");
return new Date(comps[2], comps[1], comps[0]);
}
var sortedDates = dateStrings.map(myDateParser).sort();
You can walk through the sortedDatesarray and if you find two non-consecutive dates, then you have dates with gaps between them.
您可以遍历sortedDates数组,如果您找到两个不连续的日期,那么您的日期之间存在间隔。
回答by khaliq
var dateRE = /^(\d{2})[\/\- ](\d{2})[\/\- ](\d{4})/;
function dmyOrdA(a, b){
a = a.replace(dateRE,"");
b = b.replace(dateRE,"");
if (a>b) return 1;
if (a <b) return -1;
return 0; }
function dmyOrdD(a, b){
a = a.replace(dateRE,"");
b = b.replace(dateRE,"");
if (a>b) return -1;
if (a <b) return 1;
return 0; }
function mdyOrdA(a, b){
a = a.replace(dateRE,"");
b = b.replace(dateRE,"");
if (a>b) return 1;
if (a <b) return -1;
return 0; }
function mdyOrdD(a, b){
a = a.replace(dateRE,"");
b = b.replace(dateRE,"");
if (a>b) return -1;
if (a <b) return 1;
return 0; }
dateArray = new Array("09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015");
var c = dateArray.sort( dmyOrdA );
console.log(c);
回答by TaoPR
To sort your date string ascendingly without alteration to its value, try this:
要在不更改其 value 的情况下对日期字符串进行升序排序,请尝试以下操作:
var T = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];
var sortedT = T.sort(s1,s2){
var sdate1 = s1.split('/');
var sdate2 = s2.split('/');
var date1 = s1[1]+'/'+s1[0]+'/'+s1[2];
var date2 = s2[1]+'/'+s2[0]+'/'+s2[2];
if (Date.parse(date1) > Date.parse(date2)) return 1;
else if (Date.parse(date1) < Date.parse(date2) return -1;
else return 0;
}
The resultant array sortedTshould be a sorted array of date string.
结果数组sortedT应该是日期字符串的排序数组。
NOTE:
笔记:
Your date format is stored in dd/mm/yyyybut the standard date format of JavaScript is mm/dd/yyyy. Thus, in order to parse this string to Date without using external date format library, the date string is therefore needed to be converted for compatibility during sort.
您的日期格式存储在,dd/mm/yyyy但 JavaScript 的标准日期格式是mm/dd/yyyy. 因此,为了在不使用外部日期格式库的情况下将此字符串解析为 Date,因此需要在排序期间将日期字符串转换为兼容性。

