简体   繁体   English

对作为日期的字符串数组进行排序 JavaScript

[英]Sort an array of strings that are dates JavaScript

I've tried using underscorejs, min and max methods but they can't handle strings.我尝试过使用 underscorejs、 minmax方法,但它们无法处理字符串。 From what i've read and learnt anyway, since I get infinite back from both.无论如何,从我阅读和学习的内容来看,因为我从两者中都得到了infinite回报。

My array looks like : dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]我的数组看起来像: dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]

How can I grab the last and the first date in these?我怎样才能抓住这些中的最后一个和第一个日期?

I tried using sort also that looks like : _.chain(dateData).sort().first().value() but I get back the last item in the array rather then the last date in the array.我也尝试使用看起来像这样的sort_.chain(dateData).sort().first().value()但我返回数组中的最后一项,而不是数组中的最后一个日期。

 var dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]; function dateToNum(d) { // Convert date "26/06/2016" to 20160626 d = d.split("/"); return Number(d[2]+d[1]+d[0]); } dateData.sort(function(a,b){ return dateToNum(a) - dateToNum(b); }); console.log( dateData );

To retrieve the first, last date:要检索第一个、最后一个日期:

var firstDate = dateData[0];
var lastDate  = dateData[dateData.length -1];

Basically, if you first convert all your 26/06/2016 to a date Number like 20160626 you can .sort() those numbers instead.基本上,如果您首先将所有26/06/2016转换为日期数字,例如20160626您可以.sort()这些数字。

so you're basically sorting:所以你基本上是在排序:

20140626  
20140604  
20140513  
20140720  

resulting in:导致:

[  
  "13/05/2016",  
  "04/06/2016",  
  "26/06/2016",  
  "20/07/2016"  
]

If we can format the dateStrings in a particular format, then sorting them as strings also sorts them as dates eg YYYY-MM-DD.如果我们可以将 dateStrings 格式化为特定格式,那么将它们作为字符串进行排序也会将它们作为日期进行排序,例如 YYYY-MM-DD。

You can use localeCompare to compare strings.You can use following code to sort the dates:您可以使用localeCompare来比较字符串。您可以使用以下代码对日期进行排序:

 dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"] dateData.sort(function(a, b){ var A = a.split("/"); var B = b.split("/"); var strA = [ A[2], A[1], A[0] ].join("/"); var strB = [ B[2], B[1], B[0] ].join("/"); return strA.localeCompare( strB ); }); console.log( dateData );

Once sorted, you can get the min and max dates as:排序后,您可以获得最小和最大日期:

var minDate = dateData[0];
var maxDate = dateData[ dateData.length - 1 ];

The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time. getTime() 方法根据通用时间返回指定日期的时间对应的数值。 Date.getTime() 日期.getTime()

 dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"] .map(a=>a.split('/').reverse().join('/')) .sort((a,b)=>new Date(a).getTime() - new Date(b).getTime()); console.log(dateData);

A number people have already touched on this, but you need to convert the date strings to something that can be compared in the sort function.很多人已经接触过这一点,但是您需要将日期字符串转换为可以在 sort 函数中进行比较的内容。 The one thing I haven't seen shared is how to get the first and last dates.我没有看到共享的一件事是如何获取第一个和最后一个日期。 This should do the trick:这应该可以解决问题:

//original date array
var dateData = ["04/06/2016", "13/05/2016", "20/07/2016","26/06/2016"];

//map through the original array and convert the dates to js date objects
var formattedDates = dateData.map(function(date){
    var splitDate = date.split("/")
    return new Date(splitDate[2],splitDate[1]-1,splitDate[0])
})

//sort the dates
formattedDates.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(a) - new Date(b);
});

//Now you can get the first and last dates:
var firstDate = formattedDates[0]
var lastDate = formattedDates[formattedDates.length-1];

//log to check:
console.log('first date: ', firstDate)
console.log('last date: ', lastDate)

To be easier for the subsequest operations, change the format to be like this: YYYY/MM/DD.为了便于后续操作,请将格式更改为:YYYY/MM/DD。 This way regular sorting will get you the min and max properly, and you won't need further parsing.这样,常规排序将正确地为您提供最小值和最大值,并且您不需要进一步解析。 Helper function to sort would be like this:排序的辅助函数如下所示:

for(var i=0;i<dateData.length;++i)
{
    var split = dateData[i].split("/");
    dateData[i] = split.reverse().join("/");
}

One way I know to do this is using the .sort() function for a string.我知道的一种方法是对字符串使用 .sort() 函数。 https://msdn.microsoft.com/en-us/library/4b4fbfhk(v=vs.94).aspx https://msdn.microsoft.com/en-us/library/4b4fbfhk(v=vs.94).aspx

You would have to change your array into YYYY-MM-DD您必须将数组更改为 YYYY-MM-DD

then you could have the following code那么你可以有以下代码

var dateData = ["2016/06/26", "2016/06/04", "2016/05/13", "2016/07/20"]; dateData.sort(); var first = dateData[0]; var last = dateData[dateData.length-1];

where first is the earliest date and last is the latest date其中第一个是最早的日期,最后一个是最晚的日期

You can use Array#reduce , because you need only two values and this can be achieved with a single loop. 您可以使用Array#reduce ,因为您只需要两个值,这可以通过单个循环实现。

 var dates = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"], values = dates.reduce(function (r, a, i) { function getISO(s) { return s.replace(/(.+)\\/(.+)\\/(.+)/, '$3$2$1'); } if (!i) { return { min: a, max: a }; } if (getISO(a) < getISO(r.min)) { r.min = a; } if (getISO(a) > getISO(r.max)) { r.max = a; } return r; }, {}); console.log(values); 

Roko's answer worked for me, and +1. Roko的回答对我有用,+1。 And Jose had a similar thought to me, +1...何塞和我有类似的想法,+1 ...
...There's an easier and more robust way: .valueOf() ...有一种更简单、更健壮的方法: .valueOf()

converting date string to number :将日期字符串转换为数字

const dateAsNumber = new Date(dateAsString).valueOf()

JS has a built in method/function for calculating the number of milliseconds that have passed since a date; JS 有一个内置的方法/函数,用于计算自一个日期以来经过的毫秒数; that's .valueOf(), which can be called on a Date object.那是 .valueOf(),它可以在 Date 对象上调用。 So, turn your date string into a Date object (with "new Date()" with the date string as the argument), and then convert to milliseconds.因此,将您的日期字符串转换为 Date 对象(使用“new Date()”,以日期字符串为参数),然后转换为毫秒。

After that, the normal .sort() works fine.之后,正常的 .sort() 工作正常。 As shown below, for your convenience:如下图,为了您的方便:

const arrayOfDateStrings = ["5/01/2012", "10/01/2020", "10/01/2019", "11/30/2016", "10/01/2021", "02/01/2020"];

const sortedArray = arrayOfDateStrings.sort((a,b)=>new Date(a).valueOf() - new Date(b).valueOf());

console.log(sortedArray);

Or Moment.js can be used instead of the built-in Date object/functions, that works in a very similar way.或者 Moment.js可以用来代替内置的 Date 对象/函数,它们的工作方式非常相似

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM