JS保留日期相差1分钟

时间:2019-06-16 08:48:58

标签: javascript arrays sorting ecmascript-6

保持日期相差1分钟。

给出数组

[
"2018-03-01T22:16:50.000Z",
"2018-05-07T09:54:21.000Z",
"2018-05-07T09:55:10.000Z",
"2018-05-07T09:56:09.000Z"
]

在这种情况下,结果应为

[
"2018-05-07T09:54:21.000Z",
"2018-05-07T09:55:10.000Z",
"2018-05-07T09:56:09.000Z"
]

2 个答案:

答案 0 :(得分:1)

如果下一个日期与下一个日期的差异大于1分钟,并且将其添加到数组中(如果最后一个元素与前一个元素进行比较的话),则这很令人着迷。

const dates = [
"2018-03-01T22:16:50.000Z",
"2018-05-07T09:54:21.000Z",
"2018-05-07T09:55:10.000Z",
"2018-05-07T09:56:09.000Z"
]

const result = dates.filter((date, i) => {

	if (i === dates.length -1) {
 	   var date = new Date(date)
     var prev = new Date(dates[i-1])
    
    if (((date.getTime() - prev.getTime()) / 1000 ) <= 1000) {
      return date
    }  
  } else {
    var date = new Date(date)
    var next = new Date(dates[i+1])

    if (((next.getTime() - date.getTime()) / 1000 ) <= 1000) {
      return date
    }  
  }
})

console.log(result)

答案 1 :(得分:0)

这也可以与数组中的其他值一起使用

var arr = [
"2018-03-01T22:16:50.000Z",
"2018-05-07T09:54:21.000Z",
"2018-05-07T09:55:10.000Z",
"2018-05-07T09:57:10.000Z",
"2018-05-07T09:56:09.000Z",
"2018-05-07T10:10:10.000Z",
"2018-05-07T10:11:10.000Z",
"2018-05-07T09:58:10.000Z",
]

arr.sort();

var lastitem = null,
    retArr = [];

arr.forEach(function (item, index) {
    if(lastitem < item){
        var last = new Date(lastitem);
        var newitem = new Date(item);
        var diffMs = (newitem - last); // milliseconds between last & newitem
        var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes
        if(diffMins === 1 && $.inArray(item, retArr) == -1){
          retArr.push(item);  
        } 
        if(diffMins === 1 && $.inArray(lastitem, retArr) == -1){
          retArr.push(lastitem);  
        } 
    }
  lastitem = item;  

});

console.log(retArr.sort());