计算javascript中每个数组值的差异?

时间:2017-02-08 10:31:48

标签: javascript jquery arrays node.js rethinkdb-javascript

我有以下数据集。我有一个像这样的对象数组

[{ 
    createdAt: Wed Feb 08 2017 12:16:35 GMT+0500 (Pakistan Standard Time),
    set: 'jr',
},{ 
    createdAt: Wed Feb 08 2017 12:18:36 GMT+0500 (Pakistan Standard Time),
    or: 'd',
},{ 
    createdAt: Wed Feb 08 2017 12:22:46 GMT+0500 (Pakistan Standard Time),
    or: 'd',
},]

我想计算每个createdAt之间的时差,例如从前两个createdAt字段计算它将给出“2分钟”。

3 个答案:

答案 0 :(得分:1)

首先请注意,要使其工作,日期值必须是字符串。然后,您可以使用简单的for循环遍历数组,将字符串转换为Date个对象,并将当前日期值与下一个数组元素中的日期值进行比较。从那里,您可以计算日期之间的分钟数。试试这个:



var data = [{
  createdAt: 'Wed Feb 08 2017 12:16:35 GMT+0500 (Pakistan Standard Time)',
  set: 'jr'
}, {
  createdAt: 'Wed Feb 08 2017 12:18:36 GMT+0500 (Pakistan Standard Time)',
  or: 'd'
}, {
  createdAt: 'Wed Feb 08 2017 12:22:46 GMT+0500 (Pakistan Standard Time)',
  or: 'd'
}]

var differences = [];
for (var i = 0; i < data.length - 1; i++) {
  var diff = new Date(data[i + 1].createdAt) - new Date(data[i].createdAt);
  var diffMins = new Date(diff).getMinutes();
  differences.push(diffMins);
}

console.log(differences); 
&#13;
&#13;
&#13;

请注意,上述逻辑取决于按升序排序的日期。

答案 1 :(得分:0)

var a = new Date(arr[0].createdAt);
var b = new Date(arr[1].createdAt);
var diff;

if(a > b) {
    diff = a.getTime() - b.getTime();
} else {
    diff = b.getTime() - a.getTime();
}

diff = diff/1000;

// now diff is in seconds
// calculate minutes by dividing it by 60
// use this in for loop

答案 2 :(得分:0)

将日期转换为unix时间戳,以秒为单位。然后你可以通过算术运算来计算秒数的差异,如下面的伪代码。

D

同样,你可以迭代得到每个差异。