从数组获取时间差

时间:2019-04-05 09:58:11

标签: javascript node.js typescript

我有一个像这样的数组-

[ 'State is:1Time:2019-2-3 11:45:02',  
  'State is:1Time:2019-2-3 12:45:05',  
  'State is:1Time:2019-3-4 11:45:00',  
  'State is:2Time:2019-3-5 11:45:08',  
  'State is:2Time:2019-4-5 11:45:10',  
  'State is:2Time:2019-4-5 11:45:12', ]

使用Javascript,我该如何按状态检查发生次数并减去发生次数。例如,这意味着 State 1发生了3次,我希望第一次出现State 1与时间2019-2-3 11:45:02之间的时间差 时间State 1第三次发生2019-3-4 11:45:00State 2也是如此。

1 个答案:

答案 0 :(得分:0)

您可以做到

function calculateTime() {
    var array = [ 'State is:1Time:2019-2-3 11:45:02',  
  'State is:1Time:2019-2-3 12:45:05',  
  'State is:1Time:2019-3-4 11:45:00',  
  'State is:2Time:2019-3-5 11:45:08',  
  'State is:2Time:2019-4-5 11:45:10',  
  'State is:2Time:2019-4-5 11:45:12', ];
  var previousState=0;
  var previousTime = 0;
  for(var i=0;i<array.length;i++)
  {
      var str = array[i];
  str = str.split('Time');
 var str1 = str[0].split(":");
 var str2 = str[1].split(/:{0-1}/);
 var currentState = str1[1];

 var date = new Date(str2[0].substring(1,str2[0].length));
 var currentTime = date.getTime();
 if((previousState != currentState && (i >0 )|| i ==array.length-1)  )
 {
     console.log(currentTime - previousTime);
 }
 previousState = currentState;
 previousTime = currentTime;
 }

}