For example:
I have 101.2914
and I want to obtain
1:41.291
I thought to substract the integer part of the number minus 60, but I can't because could be that final time would be 2:XX.XXX
ES6:
const string = '101.2914';
let [sec, milisec] = string.split('.');
sec = +sec;
milisec = milisec.slice(0, 3);
let mins = 0;
while(sec >= 60) {
mins += 1;
sec -= 60;
}
const result = `${mins}:${sec}.${milisec}`;
console.log(result);
Old version:
var string = '101.2914';
var array = string.split('.');
var sec = +array[0];
var milisec = array[1].slice(0, 3);
var mins = 0;
while(sec >= 60) {
mins += 1;
sec -= 60;
}
var result = mins + ':' + sec + '.' + milisec;
console.log(result);
Yo Can use a function like this as well. Here i am setting input inside the function but you can pass it while calling function.
$scope.secToMinute= function (input) {
input = 101.2914;
var min = Math.floor(input/ 60);
var second = input - (min * 60);
alert(min + ":" + second.toFixed(3));
};
I hope this may help you.
var seconds = '101.2914';
var date = new Date(0,0,0);
date.setSeconds(seconds);
var result = date.getMinutes() +':'+date.getSeconds()+'.'+seconds.split('.')[1].slice(0,3);
Related
How can I use reduce() to calculate the total of all times (in string format) in the following array?
time["00:30", "01:45", "02:33"]
times.reduce((time, nextTime) => time + nextTime, 0)
I was thinking I need to split(":"), parseInt() and some more calculations or is there an easier way to do this?
If you can use an open JavaScript library like moment.js, the following is simple and preserves your string formatted times.
Note that I'm passing in "00:00" as the default value to reduce() so that times are calculated from a zero baseline, which also follows the string formatting that we'll use for all other values in the array.
const times["00:30", "01:45", "02:33"]
const totalTime = times.reduce((time, nextTime) => {
return moment(time, "hh:mm")
.add(nextTime, "hh:mm")
.format("hh:mm");
}, "00:00");
console.log("total time -->", totalTime);
// total time --> "04:48"
If we added logging inside reduce() to view the accumulation of values:
"12:30"
"02:15"
"04:48"
"total time -->" "04:48"
Notice that the result after the first pass was "12:30". If all times in the array summed to less than one clock hour the end result may not be acceptable for your particular use case.
This worked for me, this function timer is taking 2 times hh:mm:ss and splits it, divides, and then adds them together and after, it formats it to hh:mm:ss again
function timer(tempo1, tempo2) {
var array1 = tempo1.split(":");
var tempo_seg1 =
parseInt(array1[0]) * 3600 + parseInt(array1[1]) * 60 + parseInt(array1[2]);
var array2 = tempo2.split(":");
var tempo_seg2 =
parseInt(array2[0]) * 3600 + parseInt(array2[1]) * 60 + parseInt(array2[2]);
var tempofinal = parseInt(tempo_seg1) + parseInt(tempo_seg2);
var hours = Math.floor(tempofinal / (60 * 60));
var divisorMinutes = tempofinal % (60 * 60);
var minutes = Math.floor(divisorMinutes / 60);
var divisorSeconds = divisorMinutes % 60;
var seconds = Math.ceil(divisorSeconds);
var counter = "";
if (hours < 10) {
counter = "0" + hours + ":";
} else {
counter = hours + ":";
}
if (minutes < 10) {
counter += "0" + minutes + ":";
} else {
counter += minutes + ":";
}
if (seconds < 10) {
counter += "0" + seconds;
} else {
counter += seconds;
}
return counter;
}
export default timer;
and on my React App I used this code to keep track of the times and add them calling the timer function
const updateTime = () => {
let times = [];
let times2 = [];
if (todos.length > 1) {
for (let i = 0; i < todos.length; i++) {
times.push(todos[i].time + ":00");
}
times2 = times[0];
for (let i = 1; i < times.length; i++) {
times2 = timer(times2, times[i]);
}
times2 = times2.substr(0, 5);
} else if (todos.length == 1) times2 = todos[0].time;
else times2 = "No tasks";
return times2;
};
I only wanted hh:mm but for the sake of future implementation of seconds if needed, I'm going to add ":00" (seconds) and then remove it again using
times2 = times2.substr(0, 5);
how can I sum hours:minutes:seconds in JavaScript.
I mean by
04:32:05
03:14:03
To get
07:46:08
Ive tried
var time1 = "01:00:01";
var time2 = "01:00:10";
var time3 = "01:54:00";
var time4 = "01:30:00";
var time5 = "01:00:00";
var time6 = "01:00:00";
var time7 = "01:00:00";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
var splitTime3= time3.split(':');
var splitTime4= time4.split(':');
var splitTime5= time5.split(':');
var splitTime6= time6.split(':');
var splitTime7= time7.split(':');
hour = parseInt(splitTime1[0]) + parseInt(splitTime2[0]) + parseInt(splitTime3[0]) + parseInt(splitTime4[0]) + parseInt(splitTime5[0]) + parseInt(splitTime6[0]) + parseInt(splitTime7[0])
minute = parseInt(splitTime1[1]) + parseInt(splitTime2[1]) + parseInt(splitTime3[1]) + parseInt(splitTime4[1]) + parseInt(splitTime5[1]) + parseInt(splitTime6[1]) + parseInt(splitTime7[1])
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2]) + parseInt(splitTime2[2]) + parseInt(splitTime3[2])
+ parseInt(splitTime4[2]) + parseInt(splitTime5[2]) + parseInt(splitTime6[2]) +
parseInt(splitTime7[2])
minute = minute + second/60;
second = second%60;
console.log(hour+ ":" + minute + ":"+ second)
The output I get is 8.4:24.183333333333334:11 instad of 08:24:11
any suggestions?
your making it very complex, you can reduce this by converting into Date objects and then add each date to get the sum of all dates
Understanding Date and Time in JavaScript
The problem with your code is you are including the decimal point
hour = hour + minute/60;
you need to floor it.
hour = hour + Math.floor(minute/60);
Now how to do it without a lot of repetitive code.
function toSeconds(s) {
const parts = s.split(':');
return +parts[0] * 3600 + +parts[1] * 60 + +parts[2];
}
function secondsToHHMMSS(secs) {
return Math.floor(secs / 3600).toString().padStart(2, '0') + ':' +
(Math.floor(secs / 60) % 60).toString().padStart(2, '0') + ':' +
(secs % 60).toString().padStart(2, '0');
}
const timestamps = ["01:00:01", "01:00:10", "01:54:00", "01:30:00", "01:00:00", "01:00:00", "01:00:00"];
const totalSeconds = timestamps.reduce(function(total, ts) {
return total + toSeconds(ts);
}, 0);
const result = secondsToHHMMSS(totalSeconds);
console.log(result);
If you want to sum of times then you should try this
var addTime = function (time1, time2) {
// convert to ms
var dateObject1 = new Date(time1).valueOf();
var dateObject2 = new Date(time2).valueOf();
return dateObject1 + dateObject2;
}
var time1 = new Date().setHours(4, 32, 5, 0);
var time2 = new Date().setHours(3, 14, 3, 0);
var sum = new Date(addTime(time1, time2));
var getFormatedTime = function (time) {
return time.getHours()+':'+time.getMinutes()+':'+time.getSeconds()
}
console.log(getFormatedTime(sum))
The first thing you should look into is using an Array, since you have a number of objects of the same kind.
You should ideally have something like,
const times = ["04:32:05", "03:14:03", ...]
Once you have that, this problem reduces to a classic use-case for the reduce function.
The reduce function operates on an array and accumulates the value of the operation every step to yield one value at the end.
Here's an example solution for your problem
const times = ["04:32:05", "03:14:03"]
//const times = ["01:00:01", "01:00:10","01:54:00","01:30:00"]
let finalSum = times.reduce((sum, curr) => {
//Obtain the current timestamp as an array of numbers
//[HRS, MINS, SECS]
let currTimeStamp = curr.split(":").map(token => parseInt(token));
//Add the current seconds to the total seconds so far
sum[2] += currTimeStamp[2];
//See how many minutes you got leftover as a result of that addition
const leftOverMins = Math.floor(sum[2] / 60);
//Mod by 60, to keep the seconds under 60
sum[2] %= 60;
//Add the leftover minutes to the sum operation for minutes
sum[1] += (currTimeStamp[1] + leftOverMins);
//Similar procedure as above
const leftOverHours = Math.floor(sum[1] / 60);
sum[1] %= 60;
sum[0] += (currTimeStamp[0] + leftOverHours);
sum[0] %= 24;
return sum
}, [0, 0, 0])
console.log(finalSum.join(":"))
Hello hope this answer will help you, I recommand to replace your bottom part (where you calculate) I do pretty much the same thing, but in the good order and with round to avoid decimals problems
var time1 = "01:00:01";
var time2 = "01:00:10";
var time3 = "01:54:00";
var time4 = "01:30:00";
var time5 = "01:00:00";
var time6 = "01:00:00";
var time7 = "01:00:00";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
var splitTime3= time3.split(':');
var splitTime4= time4.split(':');
var splitTime5= time5.split(':');
var splitTime6= time6.split(':');
var splitTime7= time7.split(':');
var allTimes = [splitTime1, splitTime2, splitTime3, splitTime4, splitTime5, splitTime6, splitTime7]
allTimes.forEach(element => {
hour += parseInt(element[0])
minute += parseInt(element[1])
second += parseInt(element[2])
})
minute += Math.round(second / 60);
second = second % 60;
hour += Math.round(minute / 60);
minute = minute % 60
console.log(hour+ ":" + minute + ":"+ second)
I have records in mongodb, time are string.
**Time**
00:10:40
00:40:10
01:10:20
00:43:40
00:42:40
00:30:40
00:54:10
00:47:40
00:50:40
01:05:40
00:45:40
00:51:40
00:36:40
how to calculate sum of whole times?
Is your time strings in an array?
You can use something like this:
var hours = 0;
var minutes = 0;
var seconds = 0;
var sum = '';
var myArray = ["01:40:40","03:50:50"];
var myFunction = function(){
for(var i in myArray){
hours += parseInt(myArray[i].substring(0, 2))
minutes += parseInt(myArray[i].substring(3, 5))
seconds += parseInt(myArray[i].substring(6))
}
if(seconds > 59){
minutes += parseInt(seconds / 60);
seconds = parseInt(seconds % 60);
}
if(minutes > 59){
hours += parseInt(minutes / 60);
minutes = parseInt(minutes % 60);
}
sum = hours + ":" + minutes + ":" + seconds;
console.log(sum);
}
myFunction();
Feel free to ask if you have any other questions.
**This may also work :**
var time1 = "01:00:00";
var time2 = "00:30:00";
var time3 = "00:30:00";
var hour=0;
var minute=0;
var second=0;
var splitTime1= time1.split(':');
var splitTime2= time2.split(':');
var splitTime3= time3.split(':');
hour = parseInt(splitTime1[0])+parseInt(splitTime2[0])+parseInt(splitTime3[0]);
minute = parseInt(splitTime1[1])+parseInt(splitTime2[1])+parseInt(splitTime3[1]);
hour = hour + minute/60;
minute = minute%60;
second = parseInt(splitTime1[2])+parseInt(splitTime2[2])+parseInt(splitTime3[2]);
minute = minute + second/60;
second = second%60;
alert('sum of above time= '+hour+':'+minute+':'+second);
How to parse a given amount of milliseconds (e.g. 125230.41294642858) into a time format like: minutes:seconds?
var ms = 125230.41294642858,
min = 0|(ms/1000/60),
sec = 0|(ms/1000) % 60;
alert(min + ':' + sec);
Try the following
var num = Number(theTextValue);
var seconds = Math.floor(num / 1000);
var minutes = Math.floor(seconds / 60);
var seconds = seconds - (minutes * 60);
var format = minutes + ':' + seconds
Number.prototype.toTime = function(){
var self = this/1000;
var min = (self) << 0;
var sec = (self*60) % 60;
if (sec == 0) sec = '00';
return min + ':' + sec
};
var ms = (new Number('250')).toTime();
console.log(ms);
=> '0:15'
var ms = (new Number('10500')).toTime();
console.log(ms);
=> '10:30'
Even though moment.js does not provide such functionality, if you come here and you are already using moment.js, try this:
function getFormattedMs(ms) {
var duration = moment.duration(ms);
return moment.utc(duration.asMilliseconds()).format("mm:ss");
}
This workaround in moment was introduced in this Issue.
My javascriptcode is working fine when i put alert.I need to Display time in Counter Format(Second decreasing way). Please help me in resolving this issue
<script type="text/javascript">
window.onload = function () {
//alert("request>>>");
var count = 0;
var start_actual_time = document.getElementById("timerStartTime").value;
var end_actual_time = document.getElementById("timerEndTime").value;
start_actual_time = new Date(start_actual_time);
var start_actual_time1 = new Date(start_actual_time.getTime());
start_actual_time1 = new Date(start_actual_time1);
var end_actual_time1 = new Date(end_actual_time);
var hours =end_actual_time1.getHours()- start_actual_time1.getHours();
var minutes = end_actual_time1.getMinutes() - start_actual_time1.getMinutes();
var seconds = end_actual_time1.getSeconds()- start_actual_time1.getSeconds();
seconds = hours * 3600 + minutes * 60 + seconds;
//alert ("seconds >>." +seconds);
timer(seconds);
};
function timer(seconds) {
alert("calling timer");
var s1 = Number(seconds);
var hours = Math.floor(s1 / 3600);
var minutes = Math.floor(s1 % 3600 / 60);
var s = Math.floor(s1 % 3600 % 60);
//alert("sec1" + s);
display = document.querySelector('#time');
var formatted = ((hours < 10)?("0" + hours):hours) + ":" + ((minutes < 10)?("0" + minutes):minutes) + ":" + ((s < 10)?("0" + s):s)
display.textContent = formatted ;
seconds = seconds - 1;
timer(seconds);
}
</script>
The way your code is written creates a
too much recursion
exception for me.
Therefore I have avoided recursive invokes and used javascript setInterval:
var refreshIntervalId = setInterval(function(){ timer(); }, 1000);
When your seconds reach zero, timer is stopped:
if (seconds == -1){
clearInterval(refreshIntervalId);
Link to working fiddle: http://jsfiddle.net/3ggspruf/2/