I have two values that are used for the amount of time it will take to complete a task. How can I add these values together to come up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?
The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.
Thanks!
Writing your own time and date functions can get complex. Why re-invent the wheel. Take a look at the excellent http://www.datejs.com/ date library. It handles all date and time related tasks and usage is very simple.
Here's something I had laying around. It allows for an infinite number of arguments, so you could have addTime('01:00') or addTime('01:00', '02:00', '03:00', '04:00'), etc. It's three functions long because it also verifies if the times entered are properly formatted, and if not, then it formats them. (E.g. Ensures that minutes is 2 digits long, and if hours is 1 digit long, then pad it with one zero, etc.)
You can play with it here: http://jsfiddle.net/WyxwU/
It's also here:
var totalTime = addTime('12:34', '56:12', '78:45');
document.write(totalTime);
function addTime()
{
if (arguments.length < 2)
{
if (arguments.length == 1 && isFormattedDate(arguments[0])) return arguments[0];
else return false;
}
var time1Split, time2Split, totalHours, totalMinutes;
if (isFormattedDate(arguments[0])) var totalTime = arguments[0];
else return false;
for (var i = 1; i < arguments.length; i++)
{
// Add them up
time1Split = totalTime.split(':');
time2Split = arguments[i].split(':');
totalHours = parseInt(time1Split[0]) + parseInt(time2Split[0]);
totalMinutes = parseInt(time1Split[1]) + parseInt(time2Split[1]);
// If total minutes is more than 59, then convert to hours and minutes
if (totalMinutes > 59)
{
totalHours += Math.floor(totalMinutes / 60);
totalMinutes = totalMinutes % 60;
}
totalTime = totalHours + ':' + padWithZeros(totalMinutes);
}
return totalTime;
}
function isFormattedDate(date)
{
var splitDate = date.split(':');
if (splitDate.length == 2 && (parseInt(splitDate[0]) + '').length <= 2 && (parseInt(splitDate[1]) + '').length <= 2) return true;
else return false;
}
function padWithZeros(number)
{
var lengthOfNumber = (parseInt(number) + '').length;
if (lengthOfNumber == 2) return number;
else if (lengthOfNumber == 1) return '0' + number;
else if (lengthOfNumber == 0) return '00';
else return false;
}
Here is the simple JS code for this,
var a = "2:50";
var b = "2:15";
var splitTimeStr = function(t){
var t = t.split(":");
t[0] = Number(t[0]);
t[1] = Number(t[1]);
return t;
};
var addTime = function(t1, t2){
var t1Hr = splitTimeStr(t1)[0];
var t1Min = splitTimeStr(t1)[1];
var t2Hr = splitTimeStr(t2)[0];
var t2Min = splitTimeStr(t2)[1];
var rHr = t1Hr + t2Hr;
var rMin = t1Min + t2Min;
if (rMin >= 60)
{
rMin = rMin - 60;
rHr = rHr + 1;
}
if (rMin < 10) rMin = "0" + rMin;
if (rHr < 10) rHr = "0" + rHr;
return "" + rHr + ":" + rMin;
};
document.write(addTime(a, b));
you can validate/play this with code here: http://jsfiddle.net/z24v7/
What you have to do is calculate them to a decimal by that I mean.
Strip out the hour/mins multiple that by 60 + to mins
//strip out the hours
l_hour = Number(l_time$.substr(0, l_pos));
//Strip out the mins
l_min = Number(l_time$.substr(l_pos + 1, l_time$.length));
//add the two values divided by 60 mins
l_time_decimal= Number(Math.abs(l_hour)) + Number(Math.abs(l_min)/60);
Do this for each value then deduct the two figures to give you the difference (i.e time taken). All thats left is convert it back from a decimal to a time
l_difference_in_min = l_difference * 60;
l_time_mins = l_difference_in_min%60;
l_time_hours = (l_difference_in_min - l_mins)/60;
Now just format the two to be HH:MM
I would break the problem into sub-tasks that are reusable. You have to concerns here:
Process a time string in "hh:mm" format: Converting this to minutes makes sense because it seems to be the time granularity at which you're operating.
Format a given number of minutes into a time string in "hh:mm" format.
The fact that you're adding two times together is a diversion from the actual two problems above.
Parse a time string into minutes:
function parseMinutes(s) {
var tokens = s.split(":");
return tokens[0] * 60 + parseInt(tokens[1]);
}
Format minutes into a time string:
function formatMinutes(minutes) {
function pad(n) {
return n > 9
? n
: ("0" + n);
}
var hours = Math.floor(minutes / 60),
mins = minutes % 60;
return pad(hours) + ":" + pad(mins);
}
Then your specific problem can be tackled by:
var sum = formatMinutes(parseMinutes(a) + parseMinutes(b));
Related
I tried since yesterday to find out the reverse of this formula:
I work with HART (Highway Addressable Remote Transducer) Protocol and the specification said this:
"... for the DEFAULT_VALUE, the constant-expression must resolve to an
unsigned 4-byte or 8-byte integer. example 4-byte TIME_VALUE encoding
for 05:14:26 could be expressed as: DEFAULT_VALUE =
((5*60+14)*60+26)*32000;"
this value is equal with: 603712000 -> to byte array -> 23 FB EA 00
Can anyone please help me to find the reverse formula? for example 444800000 -> to byte array -> 1A 83 1C 00.. this number first is divided with 32000 and it's equal to : 13900, and from here I want to obtain the readable time format: hh:mm:ss (like in the above example).
I made this functions but seems to not work as I expected:
secondsPassedToTime = function (seconds) {
var decimalTime = seconds / 86400;
var hour = decimalTime * 24;
var minutes = (hour % 1) * 60 // --> (hour % 1) -> get fractional part from number: 1.9 = 1 + 0.9
var seconds = (minutes % 1) * 60
hour = (~~hour).toString().length < 2 ? "0" + (~~hour).toString() : (~~hour).toString(); // --> (~~hour) -> get int from float: 1.9 = 1
minutes = (~~minutes).toString().length < 2 ? "0" + (~~minutes).toString() : (~~minutes).toString();
seconds = (~~seconds).toString().length < 2 ? "0" + (~~seconds).toString() : (~~seconds).toString();
var time = hour.toString() + ":" + minutes.toString() + ":" + seconds.toString();
return time;
};
console.log(secondsPassedToTime(13900))
here I get a possible readable format, but when I transform this to byte array is not 1a 83 1c 00 is totally another value.. 1A 82 9F 00. One of these functions doesn't work properly.
timeToHartTimeByteArray = function (time) {
var byteArray = new Array();
var regex = /^[0-9]{2}\:[0-9]{2}\:[0-9]{2}/;
if (time.match(regex)) {
time = time;
}
else {
throw "Invalid format for TIME! Format must be: hh:mm:ss";
}
var time = time.split(":");
var hours = parseFloat(time[0]) * 3600;
var minutes = parseFloat(time[1]) * 60;
var seconds = parseFloat(time[2]);
var finalTime = hours + minutes + seconds;
finalTime = finalTime * 32000;
var hexTime = finalTime.toString(16)
if (hexTime.length != 8) {
var hexTime = "0" + hexTime;
byteArray.push(hexTime.slice(0, 2))
byteArray.push(hexTime.slice(2, 4))
byteArray.push(hexTime.slice(4, 6))
byteArray.push(hexTime.slice(6, 8))
}
else {
byteArray.push(hexTime.slice(0, 2))
byteArray.push(hexTime.slice(2, 4))
byteArray.push(hexTime.slice(4, 6))
byteArray.push(hexTime.slice(6, 8))
}
return byteArray;
};
console.log(timeToHartTimeByteArray("03:51:39"))
I found the problem, it was the first function, the calculation was completely wrong:
secondsPassedToTime = function (seconds) {
var hour = seconds * 0.00027778;
var hh = (~~hour).toString().length < 2 ? "0" + (~~hour).toString() : (~~hour).toString();
var minutes = (hour - hh) * 60.000;
var mm = (~~minutes).toString().length < 2 ? "0" + (~~minutes).toString() : (~~minutes).toString();
var seconds = (minutes - mm) / 0.016667;
var ss = (~~seconds).toString().length < 2 ? "0" + (~~seconds).toString() : (~~seconds).toString();
return (hh + ":" + mm + ":" + ss)
};
console.log(secondsPassedToTime(13900))
And now with this output, the second functions convert to the correct hexadecimal value:
timeToHartTimeByteArray = function (time) {
var byteArray = new Array();
var regex = /^[0-9]{2}\:[0-9]{2}\:[0-9]{2}/;
if (time.match(regex)) {
time = time;
}
else {
throw "Invalid format for TIME! Format must be: hh:mm:ss";
}
var time = time.split(":");
var hours = parseFloat(time[0]) * 3600;
var minutes = parseFloat(time[1]) * 60;
var seconds = parseFloat(time[2]);
var finalTime = hours + minutes + seconds;
finalTime = finalTime * 32000;
var hexTime = finalTime.toString(16)
if (hexTime.length != 8) {
var hexTime = "0" + hexTime;
byteArray.push(hexTime.slice(0, 2))
byteArray.push(hexTime.slice(2, 4))
byteArray.push(hexTime.slice(4, 6))
byteArray.push(hexTime.slice(6, 8))
}
else {
byteArray.push(hexTime.slice(0, 2))
byteArray.push(hexTime.slice(2, 4))
byteArray.push(hexTime.slice(4, 6))
byteArray.push(hexTime.slice(6, 8))
}
return byteArray;
};
console.log(timeToHartTimeByteArray("03:51:40"))
I've been trying to implement the function that sums two values as hours.
"Example: 01:30 + 00:30 = 02:00"
So I have this function below that works only if the sum of the two values is equal to a round number such as the example above. But the problem is when the values are say 01:45 + 00:20 it gives me 33:05 instead of 02:05.
I've tried several combinations but nothing has worked so far.
function sumOFHoursWorked(){
var time1 = "00:45";
var time2 = "01:20";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
hour = parseInt(splitTime1[0])+parseInt(splitTime2[0]);
minute = parseInt(splitTime1[1])+parseInt(splitTime2[1]);
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2])+parseInt(splitTime2[2]);
minute = minute + second/60;
second = second%60;
var REalhourstime = ('0' + hour).slice(-2)+':'+('0' + minute).slice(-2);
alert(REalhourstime);
document.getElementById('realhorasTB').innerHTML = REalhourstime;
}
It actually depends on how your time will be, i mean it will be in mm:ss formet or hh:mm:ss or maybe hh:mm:ss:msms but for just simple second and minutes you can do something like this
function sumOFHoursWorked(){
var time1 = "00:45".split(':');
var time2 = "01:20".split(':');
let secondSum = Number(time1[1]) + Number(time2[1]);
let minSum = Number(time1[0]) + Number(time2[0]);
if(secondSum > 59){
secondSum = Math.abs(60 - secondSum);
minSum += 1;
}
if(secondSum < 10){
secondSum = `0${secondSum}`;
}
if(minSum < 10){
minSum = `0${minSum}`;
}
return `${minSum}:${secondSum}`;
}
console.log(sumOFHoursWorked());
I would convert it to minutes and subtract and then calculate hours and minutes.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("00:45", "01:20"))
It will fail for times that go over midnight, a simple less than check can fix that.
function totalMinutes (time) {
var parts = time.split(":")
return +parts[0] * 60 + +parts[1]
}
function timeDiff (time1, time2) {
var mins1 = totalMinutes(time1)
var mins2 = totalMinutes(time2)
if (mins2 < mins1) {
mins2 += 1440
}
var diff = mins2 - mins1
var hours = '0' + (Math.floor(diff/60))
var minutes = '0' + (diff - hours * 60)
return (hours.slice(-2) + ':' + minutes.slice(-2))
}
console.log(timeDiff("23:45", "00:45"))
First of all, the time1 and time2 strings are missing the seconds at the end. For example, var time1 = "00:45:00". Otherwise, your calculation will have some NaN values.
The main issue is that hour is a floating point number (~ 2.083333333333333), so ('0' + hour) is '02.083333333333333'.
You could use something like this instead: ('0' + Math.floor(hour)).
I'm currently using this function to calculate 2 fields and the results are good but sometimes missing a zero. sample
10:20 + 10:30 current output 0.10
10:20 + 10:30 I want the output to be 00.10
$(function () {
function calculate() {
time1 = $("#start").val().split(':'),
time2 = $("#end").val().split(':');
hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
hours = hours2 - hours1,
mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
} else {
mins = (mins2 + 60) - mins1;
}
// the result
$("#hours").val(hours + ':' + mins);
}
});
also when there is an invalid character I keep getting a nan message is possible to change this to 00 instead?
Instead of dealing with the strings and each value independently, you can use the javascript Date object to calculate the difference...
function calculate() {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + $('#start').val());
var time2 = new Date('01/01/2017 ' + $('#end').val());
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Set the result adding '0' to the left if needed
$("#hours").val((hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes));
}
Or even better, you can make the function independent of the DOM elements, so you can reuse it...
function calculate(startTime,endTime) {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + startTime);
var time2 = new Date('01/01/2017 ' + endTime);
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Return the response, adding '0' to the left of each field if needed.
return (hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes);
}
// Now you can use the function.
$("#hours").val(calculate($('#start').val(),$('#end').val()));
Add a function
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
and call this function before displaying result
I propose you that :
$(".calculator").on("change",function(){
var isNegative = false;
var hours = "00:00";
var inputStart = $("#start").val();
var inputEnd = $("#end").val();
if(inputStart!="" && inputEnd != ""){
// calculate only if the 2 fields have inputs
// convert to seconds (more convenient)
var seconds1 = stringToSeconds(inputStart);
var seconds2 = stringToSeconds(inputEnd);
var secondsDiff = seconds2 - seconds1;
var milliDiffs = secondsDiff * 1000;
if(milliDiffs < 0){
milliDiffs = milliDiffs *-1;
isNegative = true;
}
// Convert the difference to date
var diff = new Date(milliDiffs);
// convert the date to string
hours = diff.toUTCString();
// extract the time information in the string 00:00:00
var regex = new RegExp(/[0-9]{2}:[0-9]{2}:[0-9]{2}/);
var arr = hours.match(regex);
hours = arr[0];
// Take only hours and minutes and leave the seconds
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
// put minus in front if negative
if(isNegative){
hours = "-"+hours;
}
// Show the result
$("#hours").val(hours);
// Put back the inputs times in case there were somehow wrong
// (it's the same process)
var date1 = new Date(seconds1*1000);
var str1 = date1.toUTCString();
arr = str1.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#start").val(hours);
// idem for time 2
var date2 = new Date(seconds2*1000);
var str2 = date2.toUTCString();
arr = str2.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#end").val(hours);
}
});
function timeElementToString(timeElement){
var output = timeElement.toString();
if(timeElement < 10 && timeElement >=0)
output = "0"+output;
else if(timeElement < 0 && timeElement >=-10)
output = "-0"+Math.abs(output);
return output;
}
function stringToSeconds(input){
var hours = 0;
var arr=input.split(":");
if(arr.length==2){
hours=parseInt(arr[0]);
minutes=parseInt(arr[1]);
if(isNaN(hours)){
hours = 0;
}
if(isNaN(minutes)){
minutes = 0;
}
}
return hours*3600+60*minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="start">Start</label><input type="text" id="start" class="calculator"></input><br />
<label for="end">End</label><input type="text" id="end" class="calculator"></input><br />
<label for="hours">Hours</label><input type="text" id="hours" readonly="readonly"></input>
</form>
I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:
var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.
Any Suggestions?
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
edit:
To account for zero-padding you can do something like:
function format(x){
if (x < 10) return '0' + x;
return x;
}
var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
Convert the numerical value to a string:
var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();
If you want it to always be 6 characters long, you need to pad the values if they are < 10. For example:
var hours = date.getUTCHours();
if (hours < 10)
hours = '0' + hours.toString();
else hours = hours.toString();
var mins = date.getUTCMinutes();
if (mins < 10)
mins = '0' + mins.toString();
else mins = mins.toString();
var secs = date.getUTCSeconds();
if (secs < 10)
secs = '0' + secs.toString();
else secs = secs.toString();
var time = hours + mins + secs;
That's happening because those functions return an Integer type. If you want to add the digits themself togheter, try converting every variable to string using toString()
I am building an app using Phonegap and JQuery.
The app stores ( using window.localStorage ) a set of times (no more than 10) in the format.
HH:MM:SS.mm
There are a number of 'Zero' times in the list eg '00:00:00.00' which iphonegap, javascript
eliminate using..
function removeA(arr){
var what, a= arguments, L= a.length, ax;
while(L> 1 && arr.length){
what= a[--L];
while((ax= arr.indexOf(what))!= -1){
arr.splice(ax, 1);
}
}
return arr;
}
scores.sort();
removeA(scores,'00:00:00.00');
so that i'm left with the fastest time first, and only the times that have a value.
I need to produce from the remaining values the average of those times.
eg: 00:00:03.00
00:00:05.00
00:00:02.00
00:00:06.00
= 00:00:04.00
thanks in advance :)
var times= [ '00:00:03.00', '00:00:05.00', '00:00:02.00', '00:00:06.00'],
date = 0,
result = '';
function offsetify(t){
return t < 10 ? '0' + t : t;
}
for(var x = 0; x < times.length; x++ ) {
var tarr = times[x].split(':');
date += new Date(0, 0, 0, tarr[0], tarr[1], tarr[2].split('.')[0], tarr[2].split('.')[1]).getTime();
}
var avg = new Date(date/times.length);
result = offsetify(avg.getHours()) + ':' + offsetify(avg.getMinutes()) + ':' + offsetify(avg.getSeconds()) + '.' + offsetify(avg.getMilliseconds());
DEMO
if you are going to also have millisecond values and you want to consider them, then convert the times into millisecond. Now, add them and divide them by the number of records. Else, convert everything to seconds and find the average - you get the answer in seconds, of course.
The conversion is quite simple if take little time to think over it. Here's how to convert.
To milliseconds:
function convertToMS(timeStr) { // timeStr in format 'HH:MM:SS.mm'
var I = parseInt; // for brevity
var t = timeStr,
h = I( t.substr(0,2) ),
m = I( t.substr(3,2) ),
s = I( t.substr(6,2) ),
ms = I( t.substr(9,2) );
return h * 3600000 + m * 60000 + s * 1000 + ms;
}
To seconds:
function convertToS(timeStr) { // timeStr in format 'HH:MM:SS[.mm]' -- .mm is ignored.
var I = parseInt; // for brevity
var t = timeStr,
h = I( t.substr(0,2) ),
m = I( t.substr(3,2) ),
s = I( t.substr(6,2) );
return h * 3600 + m * 60 + s;
}
After the conversion's done, add them up and find the average.
UPDATE:
To convert back to the format 'HH:MM:SS.mm', we change back the time into 'chunks' of hours, minutes, seconds and (if applicable) milliseconds.
function chunkifyFromSec(time) { // time in s
var t = "",
h = Math.floor(time / 3600),
m = Math.floor( (t - (h * 3600)) / 60 ),
s = t - (h * 3600) - (m * 60);
return {
HH: h, MM: m, SS: s, mm: 0
};
}
function chunkifyFromMS(time) { // time in ms
var t = "",
h = Math.floor(time / 3600000),
m = Math.floor( (t - (h * 3600000)) / 60000 ),
s = Math.floor( (t - (h * 3600000) - (m * 60000)) / 1000 ),
mm = t - (h * 3600000) - (m * 600000) - (s * 1000);
return {
HH: h, MM: m, SS: s, mm: mm
};
}
Then, we return the string in the format 'HH:MM:SS.mm' using this:
function toTimeStr(chunks) {
return
(chunks.HH < 0 ? '0' : '') + chunks.HH + ":"
+= (chunks.MM < 0 ? '0' : '') + chunks.MM + ":"
+= (chunks.SS < 0 ? '0' : '') + chunks.SS + "."
+= (chunks.mm < 0 ? '0' : '') + chunks.mm
}
I don't have much experience with Javascript so I might have some syntax errors but I think you could do something like
var i = 0;
var totalTime = 0.0;
for (i=0; i < scores.length; i++) {
var hours = parseFloat(scores[i].substring(0, 2)); //get numeric value for hours
var minutes = parseFloat(scores[i].substring(3,5)); //get numeric value for minutes
var seconds = parseFloat(scores[i].substring(6)); //get numeric for the seconds
var time = ((hours * 60) + minutes) * 60 + seconds; //60 minutes in an hour, 60 seconds in a minute
totalTime += time;
}
var avgTime = totalTime/scores.length;
var avgHours = Math.floor(avgTime / 3600); //60*60
var avgHoursStr = String(avgHours);
var avgMinutes = Math.floor((avgTime % 3600) / 60); //mod to get rid of the hours
var avgMinutesStr = String(avgMinutes);
var avgSeconds = avgTime - avgHours*3600 - avgMinutes*60; //get the remainder. Can't use mod due to decimal
var avgSeconds = String(avgSeconds);
//Concat strings. Add the ":" spacers. Where necessary, add leading 0
var avgStr = (avgHoursStr.length > 1 ? "" : "0") + avgHoursStr + ":" + (avgMinutesStr.length > 1 ? "" : "0") + avgMinuteStr + ":" + avgSecondsStr;
[EDIT - Thanks to Parth Thakkar for point out my problem]
To return the answer in milliseconds or seconds:
var times = ["00:00:03.00", "00:00:05.00", "00:00:02.00", "00:00:06.00"];
function averageTimes(times,unit) {
if (!times) {
return false;
}
else {
var totalMilliseconds = 0, hours, minutes, seconds, milliseconds, parts;
for (var i = 0, len = times.length; i < len; i++) {
parts = times[i].split(':');
hours = parseInt(parts[0], 10) * 3600000;
minutes = parseInt(parts[1], 10) * 60000;
seconds = parseInt(parts[2].split('.')[0], 10) * 1000;
milliseconds = parseInt(parts[2].split('.')[1], 10);
totalMilliseconds += (hours + minutes + seconds + milliseconds);
}
if (!unit || unit.toLowerCase() == 'ms'){
return totalMilliseconds/times.length + ' milliseconds';
}
else if (unit.toLowerCase() == 's') {
return (totalMilliseconds/1000)/times.length + ' seconds';
}
}
}
// parameters:
// times: an array of times in your supplied format, 'HH:MM:SS:mm',
// unit: a string ('ms' or 's'), denoting whether to return milliseconds or seconds.
var average = averageTimes(times,'s');
console.log(average);
JS Fiddle demo.
References:
for(){/*...*/} loop.
parseInt().
split().
toLowerCase().