This question already has answers here:
How to perform an integer division, and separately get the remainder, in JavaScript?
(18 answers)
Closed 7 years ago.
So far I have been able to find the sum of min and sec store in array
var time = ["13:24", "4:28", "7:29"];
var min = 0;
var sec = 0;
for (k in time){
min += +time[k].split(":")[0];
sec += +time[k].split(":")[1];
}
var rem = sec % 60;
min += rem;
alert(min+'-'+sec); //25-81
my desired output it 25-21
I think the desired o/p is 25-21
var time = ["13:24", "4:28", "7:29"];
var min = 0;
var sec = 0;
var minsec = time.forEach(function(time) {
var parts = time.split(":")
min += +parts[0];
sec += +parts[1];
});
//Add the whole minutes from the seconds ie if seconds is 130 then 2 minuste to be added to min
min += Math.floor(sec / 60);
//then the rest 10 secs to be added to sec
sec = sec % 60;
alert(min + '-' + sec);
Your sum is wrong. You're adding the modulo of sec to min. That means if you were on 59 seconds, you'd add 59 minutes to your sum.
Instead you should add the division of sec, and set sec to the modulo:
min += Math.floor(sec / 60);
sec %= 60;
This way 69 seconds would translate to 1 minute and 9 seconds, whereas your current code would compute 9 minutes and 69 seconds.
Related
This question already has answers here:
Convert seconds to days, hours, minutes and seconds
(12 answers)
Closed 2 years ago.
I have tried different functions I found in SO but none give me a precise output.
I did one variant of this (adding days and changing to d:h:m)
const convertMinsToHrsMins = (mins) => {
let h = Math.floor(mins / 60);
let m = mins % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
return `${h}:${m}`;
}
my last attempt:
// Convert Minutes to Days Hours Minutes
const convertMinutes = (totalMinutes) => {
let Days = Math.floor((totalMinutes / 1440) % 60)
let Hours = Math.floor(totalMinutes / 60)
let Minutes = Math.round(totalMinutes % 60)
let ret = ''
if (Days > 0) {
ret += '' + Days + 'd ' + (Hours < 10 ? '0' : '')
}
ret += '' + Hours + 'h ' + (Minutes < 10 ? '0' : '')
ret += '' + Minutes + 'm'
return ret
}
totalMinutes receive a sum of different inputs(all in minutes!). I need this function to work as close as precise as possible. e.g.: convertMinutes(totalminutes)
937d 23h 59m 8d 00h 01m
Convert 1 day, 1 hour and 1 minute into minutes; subtract one day from your input till you can't anymore; then subtract one hour from your input till you can't anymore; then subtract one minute from your input till you can't anymore or either return the rest. You have to respect that order. Here is a function that mets your necessity:
function converter(minutes)
{
dates=[1440,60,1]
output=[0,0,0];
for(x=0; x<3; x++)
{
while(minutes>=dates[x])
{
minutes-=dates[x]
output[x]++
}
}
return output[0]+"Days;"+output[1]+"Hours;"+output[2]+"Minutes."
}
Use division to get the days, then use modulo to get the remaining minutes which don't sum up to a full day. Use the remaining minutes and and do the same with hours (division and modulo).
const convertMinutes = (totalMinutes) => {
const minutesInDay = 24 * 60;
const minutesInHour = 60;
let days = Math.floor(totalMinutes / minutesInDay);
let remainingMinutes = totalMinutes % minutesInDay;
let hours = Math.floor(remainingMinutes / minutesInHour);
let minutes = remainingMinutes % minutesInHour;
return `${days}d:${hours}h:${minutes}`;
}
We are using a clock system for our Moon Research with 28 hours,
Here is how we are attempting to create it in Canvas HTML,
* 1 minutes = 56 seconds
* 1 hours = 56 minutes
in this basis, we are trying to create an analog that runs for 112 minutes.
To achieve this we used the following two code bases for w3schools,
- https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_countdown
digital clock value used to generate information for the analog clock
- https://www.w3schools.com/graphics/tryit.asp?filename=trycanvas_clock_start
fundamental Earth clock used to generate the 28-hour clock with 112 minutes ticks in the clock face.
we are not able to make the clock run for 56 seconds and the minute shift accurately. Can you please help us with the corrections. Thank you.
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2021 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate + now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor((distance) / (1000 * (55.54920598892) * (55.54920598892) * 28));
var hours = Math.floor(((distance) % (1000 * (55.54920598892) * (55.54920598892) * 28)) / (1000 * (55.54920598892) * (55.54920598892)));
var hours = Math.floor(((distance) % (1000 * (55.54920598892) * (55.54920598892) * 28)) / (1000 * (55.54920598892) * (55.54920598892)));
var minutes = Math.floor(((distance) % (1000 * (55.54920598892) * (55.54920598892))) / (1000 * (55.54920598892)));
var seconds = Math.floor(((distance - 75) % (1000 * (55.54920598892))) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
</style>
</head>
<body>
<p id="demo"></p>
Current Result: the minute changes at 34 second mark
Expected Result: instead of 56 second mark.
additional problem faced: the ticking time waits for 60 seconds before 56 second shifts. Hence delaying a few second shifts in middle.
I have to admit I'm not quite sure what was the initial problem(s) with your code.
But since you are defining your units relations at one level distance (ms => sec => minutes => hrs => days), you may find it clearer to keep this relational logic in your code.
What you have initially is the distance in ms between your two dates.
You can then calculate the total number of your_seconds this distance represents, using your own definition of a second (ms_per_sec in the snippet below). From there you can walk up to the number of days.
Then, you just have to get the modulus of the total over the base you defined.
Note that since you are now not dealing with real Earth seconds, you will have to handle your animation loop on an other base than the setInterval(fn, 1000), since ther could be some your_seconds that would fall on two different real seconds. Instead, you better use a requestAnimationFrame loop, which will fire at every screen refresh.
// our constants
var ms_per_sec = 300; // 1000
var sec_per_min = 7; // 55.54920598892;
var min_per_hr = 3; // 55.54920598892;
var hrs_per_day = 28;
// let's make our target date at some fixed distance in our own time system
var countDownDate = new Date().getTime() +
(1 * hrs_per_day * min_per_hr * sec_per_min * ms_per_sec) + // 1 day
(2 * min_per_hr * sec_per_min * ms_per_sec) + // two hours
(1 * sec_per_min * ms_per_sec) + // 1 minutes
(5 * ms_per_sec); // 5 seconds
// Update the count down every frame
function loop() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var total_ms = (countDownDate - now);
// from here our values are based on our own time system
var total_seconds = (total_ms / ms_per_sec);
var total_minutes = (total_seconds / sec_per_min);
var total_hours = (total_minutes / min_per_hr);
var total_days = (total_hours / hrs_per_day);
var days = Math.floor(total_days);
var hours = Math.floor(total_hours % hrs_per_day);
var minutes = Math.floor(total_minutes % min_per_hr);
var seconds = Math.floor(total_seconds % sec_per_min);
// Output the result in an element with id="demo"
document.getElementById("demo").textContent = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (total_ms < 0) {
document.getElementById("demo").innerHTML = "EXPIRED";
return;
}
requestAnimationFrame(loop);
}
loop();
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
}
<p id="demo"></p>
help me with this one problem. I am confused how to convert second to years, days, hours, minutes and second in JavaScript. This below as an example
convertSeconds(10000)) // 2 hours, 46 minutes and 40 seconds
convertSeconds(62)) // 1 minutes and 2 seconds
convertSeconds(2000000)) // 23 days, 3 hours, 33 minutes and 20 seconds
convertSeconds(126144060)) // 4 years and 1 minutes
I know this task needs modulus just like below :
var days = Math.floor(seconds / (3600*24))
seconds -= days*3600*24
var hrs = Math.floor(seconds / 3600)
seconds -= hrs*3600
var minutes = Math.floor(seconds / 60)
seconds -= minutes*60
But it doesn't print as I want it like in my comments. How to console like that. Thank you
if I understand your question, the solution could be:
function convertSeconds(secT){
var seconds = secT % 60;
var minutes = ((secT - seconds)/60) % 60;
var hours = (secT - seconds - (minutes * 60)) / 3600 % 3600;
//EDIT
var print = "";
If(hours!=0){
print = print + hours + " hours ";
}
if(minutes!=0){
print = print + minutes + " minutes ";
}
if(seconds!=0){
print = print + seconds + " seconds ";
}
alert(print);
}
If I have the number of minutes, say 476, which equals 7 hours and 56 minutes and I need to round this number up to the nearest half hour, so in this instance I need to round 476 so that it equals to 8 hours. How could I do this in moment js?
You can use following logic:
Logic:
Get the total number of hours by dividing minutes by 60.
Get remainder minutes using mins % 60.
If mins is between 15 and 45, we can round it to 30.
If it is less than 15 or more than 45, we can round it to 0`.
If mins is greater than or equal to 45, we will increment hour by 1.
function getTime(min){
var hours = Math.floor(min/60);
var mins = min % 60;
console.log('remainder mins: ', mins)
if(mins >= 15 && mins < 45)
mins = 30;
else{
hours += mins > 45 ? 1 : 0;
mins = 0;
}
return "" + hours + (mins ? ":" + mins : "");
}
console.log(getTime(476))
console.log(getTime(446))
console.log(getTime(426))
console.log(getTime(576))
I've set up a countdown timer with 1 sec interval and increment / decrement in mill secs..
I then searched for something that would give me the value in minutes/seconds. I came up with the following:
var timer = 130000;
var mins = Math.floor((timer % 36e5) / 6e4),
secs = Math.floor((timer % 6e4) / 1000);
The above code works on Safari, Chrome and Firefox with no problem. When I get to Internet Explorer, it doesn't work at all.
Is there another way of doing it that would work on all browsers?
Try with removing the exponetial.
var timer = 130000;
var mins = Math.floor((timer % 3600000) / 60000),
secs = Math.floor((timer % 60000) / 1000);
Read more about Exponential Notation.
An Exponential Notation if number with format a x 10^n, where 1<= a < 10 and n is integer with positive or negative value.
For example:
36e5
= 36 x 10^5
= 36 x 100000
= 3600000
ans so on.