Click here to Skip to main content
15,886,065 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the date array as follows:
["09/23/2019", "08/23/2019", "07/23/2019", "06/23/2019", "05/23/2019", "04/23/2019", "03/23/2019", "02/23/2019", "01/23/2019", "12/23/2018"]


I need to reverse it and start from 12/23/2018 instead.

I tried
dates.reverse
but it completely messes up the format and print unsorted date. Also tried
dates.sort()
and it sorts the dates from 01/2019 to 09/2019 and prints 12/2018 at the very end.

What I have tried:

stDate = 11/20/2018
etDate = 09/19/2019
 var Endnow = etDate.clone();
        var Endday = etDate.date();

 while(Endnow.isAfter(stDate)) {
                    var month = Endnow.clone().endOf("month");
                    if (Endnow.date() < Endday && Endday <= month.date()) {
                        Endnow.date(Endday);
                    }
                    dates.push(Endnow.format("MM/DD/YYYY"));
dates.reverse();
dates.sort();
                    Endnow = Endnow.clone().subtract({"months": 1});
                }
Posted
Updated 20-Nov-18 11:18am
Comments
Daniel Pfeffer 20-Nov-18 15:19pm    
I fail to see why dates.reverse() doesn't give you what you want. It reverses the order of the elements of the array, without caring what the values are. An array in ascending order would become an array in descending order.
If your array is not in order, you will have to write a custom sorting function. As you have discovered, dates in US format cannot be sorted as if they were strings.

1 solution

JavaScript
function datecomp( d1, d2 )
{
  var a1 = d1.split("/");
  var a2 = d2.split("/");
  a1 = a1[2] + a1[0] + a1[1];
  a2 = a2[2] + a2[0] + a2[1];
  return (parseInt(a1) - parseInt(a2));
}

dates.sort(datecomp);
 
Share this answer
 
Comments
Member 14013562 28-Nov-18 13:07pm    
Works great. Thank you much.
CPallini 29-Nov-18 2:46am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900