0

I have dynamic date and time being generated and I need to sort them in descending order using JavaScript.

my data is in the below format.

var array= ["25-Jul-2017 12:46:39 pm","25-Jul-2017 12:52:23 pm","25-Jul-2017 12:47:18 pm"];

Anyone help would be appreciated.

Basil Bourque
  • 218,480
  • 72
  • 657
  • 915
reddy
  • 57
  • 2
  • 7

3 Answers3

1

Here is the working code for you:

var array = ["25-Jul-2017 12:46:39 pm", "25-Jul-2017 12:52:23 pm", "25-Jul-2017 12:47:18 pm", "25-Jul-2017 12:59:18 pm"];

array.sort((a, b) => new Date(b).getTime() - new Date(a).getTime())

console.log(array)
Milan Chheda
  • 7,851
  • 3
  • 18
  • 35
0

var array = ["25-Jul-2017 12:46:39 pm", "25-Jul-2017 12:52:23 pm", "25-Jul-2017 12:47:18 pm"];

array.sort(function(a, b) {
  return new Date(b) - new Date(a);
});

console.log(array);
Milan Chheda
  • 7,851
  • 3
  • 18
  • 35
Ryan Tsui
  • 759
  • 3
  • 14
  • First its missing explanation. Second, please check other answer. Its already covered – Rajesh Jul 25 '17 at 07:01
  • Agree with @Rajesh. It's covered. Secondly, start using code editor so that people can see the output. And lastly, yes, you need to add some explanation about your answer. – Milan Chheda Jul 25 '17 at 07:02
  • 1
    Adding to @MilanChheda comment, `<>` icon is used to launch code editor. You can put your *CSS/HTML/JS* code and make it executable. This helps people to verify you code. – Rajesh Jul 25 '17 at 07:03
0

DEMO

var array= ["25-Jul-2017 12:46:39 pm","25-Jul-2017 12:52:23 pm","25-Jul-2017 12:47:18 pm"];
var dateAr = [];

for(var i=0;i<array.length;i++){
 dateAr.push(new Date(array[i].replace(/-/g,'/')).getTime()); //convert to milisecond
}


var sortAr = dateAr.sort(function (a, b) {  return a - b;  }); //sort it

var resArr = [];
for(var i=0;i<array.length;i++){
 resArr.push(new Date(sortAr[i])); //make date object
}
console.log(resArr);

Convert to millisecond from Date , and then sort it. and make Date object from millisecond. use this replace(/-/g,'/') to replace date string, it works in all browser.

Durga
  • 13,489
  • 2
  • 19
  • 40