Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a string date array

Tags:

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;       } 
like image 558
Suyog Sawant Avatar asked Jun 07 '15 07:06

Suyog Sawant


People also ask

How do you sort an array of date strings?

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.

How do I sort a string by date?

To sort a Python date string list using the sort function, you'll have to convert the dates in objects and apply the sort on them. For this you can use the key named attribute of the sort function and provide it a lambda that creates a datetime object for each date and compares them based on this date object.

How do you sort an array by date?

To sort an array of objects by date property: Call the sort() method on the array. Subtract the date in the second object from the date in the first. Return the result.

How do I sort a string by date in Swift?

To properly sort it you first need to convert your tSFDATE string to Date and then sort it. let dateFormatter = DateFormatter() dateFormatter. dateFormat = "dd/MM/yyyy - HH:mm:ss" let sortedArray = trackingListArr. sorted { dateFormatter.

How do I sort an array in ascending order?

Show activity on this post. I want to sort an array in ascending order. The dates are in string format Show activity on this post. There is no need to convert Strings to Dates or use 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.

How do I sort a date string in JavaScript?

The resultant array sortedT should be a sorted array of date string. Your date format is stored in dd/mm/yyyy but 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.

How do I sort a date array in SDF?

Date [] arrayOfDates = new Date [dates.length]; for (int index = 0; index < dates.length; index++) { arrayOfDates [index] = sdf.parse (dates [index]); } Then sort the arrayOfDates and if you need to, use the SimpleDateFormat to format the results back to the dates array...

How to convert string array to date array?

The better way would be to convert the String array to an array of Date Then sort the arrayOfDates and if you need to, use the SimpleDateFormat to format the results back to the dates array...


2 Answers

The Simple Solution

There is no need to convert Strings to Dates or use 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.

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.

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>
like image 187
Roberto Avatar answered Oct 01 '22 23:10

Roberto


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 sort method accepts, in order to achieve this:

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 sort method:

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 createSorter call.

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 sortedDates array and if you find two non-consecutive dates, then you have dates with gaps between them.

like image 32
Cristik Avatar answered Oct 01 '22 23:10

Cristik