How to Sort Data time stamp in javascript

1.2k Views Asked by At

I have an array with date time stamp. The format is eg. 11/6/2015 15-47-35.501

I have to get the maximum/ latest DateTime stamp from this array. So applied the logic of sorting but not working. And I have to take this format only otherwise previous records will not work If I take other formats.

Code snippet is

function somefunction()
{
var creation_dt_newarr = ["11/6/2015 15-47-35.501","11/6/2015 16-19-32.939","11/6/2015 18-31-31.343"]

  creation_dt_newarr = creation_dt_arr.sort(sortFunction);
  var replaced_data = creation_dt_newarr[creation_dt_newarr.length-1];
                        var max_creation_dt_res = replaced_data;
}


function sortFunction(a,b){
    var dateA = new Date(a).getTime();
    var dateB = new Date(b).getTime();
    return dateA > dateB ? 1 : -1;
};

Please help me out how this will work. Thanks in advance.

2

There are 2 best solutions below

0
On BEST ANSWER

This could help:

function somefunction()
{
var creation_dt_newarr = ["11/6/2015 15-47-35.501","11/6/2015 16-19-32.939","11/6/2015 18-31-31.343"];
  //do some preprocessing if that is OK the last three digits like: .501
  creation_dt_newarr.forEach(function(element,i){
      creation_dt_newarr[i] = Date.parse(element.slice(0,-4).replace(/-/g,':')); 
  });
  //use Math.max to get the max date and 
  //to get the result as a date string use the new Date()
  return new Date(Math.max.apply(null, creation_dt_newarr));
}

console.log(somefunction());
0
On

You need to convert that date to a format that works. On the Google Chrome console, I tried creating a date in your format:

new Date('11/6/2015 15-47-35.501')
Invalid Date

However, if you replace the - and . in the time part with :, it does parse the date:

new Date('11/6/2015 15-47-35.501'.replace(/[-.]/g, ':'));
Fri Nov 06 2015 15:47:35 GMT-0800 (PST)

Based on that, we can adapt your sort function to:

function sortFunction(a,b) {
    var dateA = new Date(a.replace(/[-.]/g, ':')).getTime();
    var dateB = new Date(b.replace(/[-.]/g, ':')).getTime();
    return dateA > dateB ? 1 : -1;
};

I am not certain the time is being parsed correctly -- I'm assuming the last part after the period is milliseconds. You should confirm it is being parsed correctly and as the commenter suggested, storing the time as a timestamp would of course be nicer.