如何对 javascript 中的数据时间戳进行排序

How to Sort Data time stamp in javascript

我有一个带有日期时间戳的数组。格式是例如。 11/6/2015 15-47-35.501

我必须从这个数组中获取最大/最新的日期时间戳。因此应用了排序逻辑但不起作用。而且我必须只采用这种格式,否则以前的记录将无法使用如果我采用其他格式。

代码片段是

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;
};

请帮我看看这将如何工作。提前致谢。

您需要将该日期转换为有效的格式。在 Google Chrome 控制台上,我尝试以您的格式创建日期:

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

但是,如果将时间部分中的 -. 替换为 :,它会解析日期:

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

基于此,我们可以将您的排序功能调整为:

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;
};

我不确定时间是否被正确解析 -- 我假设时间段之后的最后一部分是毫秒。您应该确认它被正确解析,并且正如评论者所建议的那样,将时间存储为时间戳当然会更好。

这可能有帮助:

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());