Horace Heaven Horace Heaven - 1 month ago 8
Javascript Question

How to calculate average time

how to calculate average time with 11:59:00 PM and 12:00:00 AM so that it can be 11:59:30 PM. currently this code is giving me 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;
}

Answer

This is a function for if you are looking for an average time given a set of times, regardless of date, given a 24 hr period. It works for 12am - 12pm but not 12pm - 12am (because that spans 2 days). If you are spanning days, you must use my first answer which requires the entire date be given in the time being evaluated.

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