如何计算平均时间

时间:2013-09-18 19:33:22

标签: javascript algorithm datetime angularjs time

如何计算11:59:00 PM和12:00:00 AM的平均时间,以便它可以在晚上11:59:30。目前这段代码给了我11:59:30

       var convertTimeToMilliSecondsTest = function(time) {
                  var startDate = "1970/01/01";                         
       if(time.indexOf("AM") != -1) {
          newTime = time.replace("AM", " AM");
       } else if(time.indexOf("PM") != -1) {
          newTime = time.replace("PM", " PM");
       }
          var dateString = startDate + " " + newTime;
          var date = new Date(dateString.replace(/-/g, '/'));                                 
          return date.getTime();
       }

         var calculateAverageTimeToBed = function(dataset) {
                 var totalTimeInMilliSeconds = 0;

                 for(var i = 0;i < dataset.length; ++i) {
                       totalTimeInMilliSeconds += convertTimeToMilliSecondsTest(dataset[i].startTime);
                 }

                 var averageTimeInBed = totalTimeInMilliSeconds / dataset.length;

                 return averageTimeInBed;
          }

4 个答案:

答案 0 :(得分:3)

在计算中使用整个日期(以天为单位)。这是一种方法:

jsFiddle

var date1 = '2013-09-17 11:59:00 PM';
var date2 = '2013-09-18 12:00:00 AM';

var d1msecs = new Date(date1).getTime(); // get milliseconds
var d2msecs = new Date(date2).getTime(); // get milliseconds

var avgTime = (d1msecs + d2msecs) / 2;
console.log(avgTime);

var result = new Date(avgTime);
alert(result);

答案 1 :(得分:0)

这是一个函数,如果您在24小时内查找给定一组时间的平均时间,无论日期如何。它适用于上午12点至中午12点,但不是下午12点 - 上午12点(因为它跨越2天)。如果您正在跨越几天,则必须使用我的第一个答案,该答案要求在评估的时间内给出整个日期。

jsFiddle

// function will determine average time given a set of 
// times in a 24 hr. period, i.e. 12am - 12pm
// it does NOT work for a 24 hr. period from 12pm - 12am
var times = ['11:59:00 AM', '12:00:00 AM'];

// function accepts an array of times as the argument
// requires time to be structured as above
function getAverageTime(times) {
    var count = times.length
    var timesInSeconds = [];
    // loop through times
    for (var i =0; i < count; i++) {
        // parse
        var pieces = times[i].split(':');
        var ampm = pieces[2].split(' ');
        var hrs = Number(pieces[0]);
        var mins = Number(pieces[1]);
        var secs = Number(ampm[0]);
        var ampm = ampm[1];
        // convert to 24 hr format (military time)
        if (ampm == 'PM') hrs = hrs + 12;   
        // find value in seconds of time
        var totalSecs = hrs * 60 * 60;
        totalSecs += mins * 60;
        totalSecs += secs;
        // add to array
        timesInSeconds[i] = totalSecs;
    }
    // find average timesInSeconds
    var total = 0;
    console.log(timesInSeconds);
    for (var j =0; j < count; j++) {
        total = total + Number(timesInSeconds[j]);
    }
    var avg = Math.round(total / count);
    console.log('avg secs: '+avg);
    // turn seconds back into a time
    var avgMins = Math.floor(avg/60);
    var avgSecs = avg - (60 * avgMins);
    var avgHrs = Math.floor(avgMins/60);
    console.log('hours: '+avgHrs);
    avgMins = avgMins - (60 * avgHrs);
    // convert back to 12 hr. format
    var avgAmpm = 'AM';
    if (avgHrs > 12) {
        avgAmpm = 'PM';
        avgHrs = avgHrs - 12;
    }
    // add leading zeros for seconds, minutes
    avgSecs = ('0' + avgSecs).slice(-2);
    avgMins = ('0' + avgMins).slice(-2);
    // your answer
    return avgHrs+':'+avgMins+':'+avgSecs+' '+avgAmpm;
}

// execute
alert(getAverageTime(times));

答案 2 :(得分:0)

这已经很老了,所以我虽然使用Aidan Sheriff的SetFullYear()评论发布了一个snippit。它会返回今天所有日期的平均时间(小时,分钟和秒)。

&#13;
&#13;
let dateArray = [new Date('Sat Oct 15 2016 07:09:00 GMT+0800 (MYT)'), new Date('Mon Oct 17 2016 06:48:00 GMT+0800 (MYT)'), new Date('Tue Oct 18 2016 08:38:00 GMT+0800 (MYT)')];

function getAverageTime(array) {
  let sum = 0;
  array.map(function(d) {
    let now = new Date();
    let startDay = d.setFullYear(now.getFullYear(), now.getMonth(), now.getDate());
    sum += startDay;
  });

  return new Date(sum / dateArray.length);
}

console.log(getAverageTime(dateArray));
&#13;
&#13;
&#13;

答案 3 :(得分:0)

假设适用于以下情况: [23:30,00:30,01:30]您想要得到00:30的结果,那么以下内容适用于您:

const ONE_DAY_IN_MILLISECONDS = 24 * 3600 * 1000;

function calculateAverageOfHours(times, minTime){
  let timestamps = times.map(getTimePartInMilliseconds);
  let minTimestamp = getTimePartInMilliseconds(minTime);
  
  let average = 0;
  timestamps.forEach(t => {
    average += getMillisecondsFromTimeTillMinTime(t, minTimestamp) / timestamps.length;
  });
  
  const millisecondsFromStartOfDay = (minTimestamp + average) % ONE_DAY_IN_MILLISECONDS;
  
  return new Date(0,0,0,
                 Math.trunc(millisecondsFromStartOfDay / (3600000)),
                 Math.trunc(millisecondsFromStartOfDay % 3600000 / (60000)),
                 Math.trunc(millisecondsFromStartOfDay % 10000 / 1000));
}

function getMillisecondsFromTimeTillMinTime(time, minTime){
  if(time < minTime){
    return ONE_DAY_IN_MILLISECONDS - minTime + time;
  }
  
  return time - minTime;
}

function getTimePartInMilliseconds(t){
  return (t.getHours() * 3600 +
         t.getMinutes() * 60 +
         t.getSeconds()) * 1000 + t.getMilliseconds();
}

// The year, month and date are not relevant.
let times = [
  new Date(2020, 8, 3, 23, 30, 0),
  new Date(2020, 9, 1, 0, 30, 0),
  new Date(2020, 9, 2, 1, 30, 0)
];

console.log(calculateAverageOfHours(times, new Date(2020,8,30,22,0,0))); 
// output: Dec 31 1899 00:30:00

它计算相对于最小时间的平均时间(例如:如果minTime 是22:00,则00:30和minTime之间的差将是02:30。另一方面,如果minTime为01:00,则00:30与minTime之差为23:30。假定数组中的时间大于minTime

将数组中每个项目与minTime之间的持续时间相加并除以数组中项目的数量。该结果是接下来加到minTime的平均值。结果可能会产生大于24小时的持续时间,因此取模运算将缩短日期,仅保留毫秒数的时间。