Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
          }
like image 860
Horace Heaven Avatar asked Mar 23 '23 09:03

Horace Heaven


1 Answers

Use the entire date (with days) in your calculation. Here is one way to do it:

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);
like image 200
inorganik Avatar answered Apr 06 '23 03:04

inorganik