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;
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With