4

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

       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

4 回答 4

5

在计算中使用整个日期(包括天数)。这是一种方法:

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);
于 2013-09-18T19:47:57.150 回答
2

如果您正在寻找给定一组时间的平均时间,无论日期如何,给定 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));
于 2013-09-19T20:25:43.080 回答
0

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

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

于 2016-10-24T09:57:17.343 回答
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 和minTime02:30 之间的差异。另一方面,如果minTime是 01:00,那么 00:30 和minTime将23:30)。假定数组中的时间大于minTime

数组中每个项目之间的持续时间 和minTime相加并除以数组中的项目数。这个结果是下一个被添加到的平均值minTime。结果可能会产生大于 24 小时的持续时间,因此模运算将缩短天数,只留下以毫秒为单位的时间。

于 2020-10-02T13:59:49.263 回答