Convert second to years, days, hours, minutes and seconds - javascript

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);
}

Related

Is my modulo use wrong or is there a Math.floor rounding error happening with my seconds to minutes calculation?

SOLVED: Seems it's a problem that only exists in Codepen. Running code in a different environment didn't reproduce the problem.
Am writing code to split seconds into years, days, minutes, seconds. I'm getting some unexpected results: eg 3600 seconds comes out as 1 hour. But 3599 seconds comes out as 60 minutes and 59 seconds.
Firstly, there should never be 60 minutes. This should be 1 hour. But that aside the actual result is wrong.
Is there some error in my calculation logic, or is there a funky rounding error going on using modulo and Math.floor? Thanks!
function convertFromSeconds(time) {
const minute = 60
const hour = 60 * minute; //3600
const day = 24 * hour; // 86400
const year = 365 * day //31536000
const years = Math.floor(time / year)
const days = Math.floor((time % year) / day)
const hours = Math.floor((time % day) / hour)
const minutes = Math.floor((time % hour) / minute)
const seconds = time % minute;
// Rest of code formats the above result into a string for output
}
function convertFromSeconds(time) {
const minute = 60
const hour = 60 * minute; //3600
const day = 24 * hour; // 86400
const year = 365 * day //31536000
const years = Math.floor(time / year)
const days = Math.floor((time % year) / day)
const hours = Math.floor((time % day) / hour)
const minutes = Math.floor((time % hour) / minute)
const seconds = time % minute;
// Rest of code formats the above result into a string for output
return { years, days, hours, minutes, seconds }
}
console.log('3600:', convertFromSeconds(3600))
console.log('3599:', convertFromSeconds(3599))

how to set display on countdown timer (javascript)

I used the snippet below to create a countdown timer.
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's 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 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 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);
</script>
How do I set the output (display) like so:
If the remaining time is still above 1 month, then display only the month.
If the remaining time is under 1 month, then display only days,
If the remaining time is below 24 hours, display the hours and minutes
If the remaining time is below 1 hour, display the minutes and seconds.
Thanks
first add a calculation for number of months left
then add a function that limits the times like so
const displayRemaining = () => {
if (/* there are months remaining */) return months + " months";
if (/* there are days remaining */) return days + " days";
if (/* there are hours remaining */) return hours + " hours";
if (/* there are days remaining */) return minutes + ":" + seconds + " m:s";
return "you have gone back in time or smth idk";
}

Countdown can't be set to more than two days ahead

I have found a javascript code for a countdown timer in the internet and changed it a little bit to use it as I want.. It basically works fine, but as soon as I set the start date to more than 2 days ahead it doesn't to what it's supposed to. If I e.g. set it to three days ahead, as shown in the code below, it doesn't become a 72 hours countdown, but a 12 hours countdown.
I'm not sure whats the problem, because I can set up a 24 or a 48 hours countdown without any issues.
(function() {
var start = new Date;
start.setHours(18, 02, 20);
function pad(num) {
return ("0" + parseInt(num)).substr(-2);
}
function tick() {
var now = new Date;
var weekend = now.getDay();
if (now > start) {
start.setDate(start.getDate() + 3);
}
var remain = ((start - now) / 1000);
var hh = pad((remain / 60 / 60) % 60);
var mm = pad((remain / 60) % 60);
var ss = pad(remain % 60);
var distance = start - now;
document.getElementById('demo').innerHTML = hh + ":" + mm + ":" + ss
setTimeout(tick, 1000);
}
document.addEventListener('DOMContentLoaded', tick);
})();
The following line is the cause:
var hh = pad((remain / 60 / 60) % 60);
This caps the hours at 60 due to the % 60 (mod 60). 48 hours is less than 60 so it works. 72 hours will get translated to 12 (72 % 60 == 12).

How to create a timer loop which will work after page refreshing?

I have created my own countdown and it seems that I'm missing a part, whenever I refresh the page it also refresh the timer itself. I am looking to maximize the performance with that script so how can I make it looping infinitely?
Here is the code:
function startGRBTimer(duration, display) {
var timer = duration,
hours, minutes, seconds;
setInterval(function() {
days = parseInt(timer / (24 * 60 * 60), 10);
hours = parseInt(timer % (24 * 60 * 60) / (60 * 60), 10);
minutes = parseInt(timer % (60 * 60) / 60, 10);
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = days + "d" + " " + hours + "h " + minutes + "m " + seconds + "s";
--timer;
if (timer <= 0) {
timer = duration;
}
}, 1000);
}
var display = document.querySelector("#grb");
startGRBTimer(60, display);
That's just the way this code works, there is nothing wrong with it. Every time you refresh the page, the script gets re-run, and the var timer = duration, hours, minutes, seconds; is created whenever the page is loaded.
You should look into creating first, and then storing the variable to the user's local storage, and have your program read the info from that variable (or array).
You need to do some job independently from your web application, with ability to live after page refresh, right?
It's highly likely that ServiceWorkers will be useful for you.
We could "misuse" window.name (see documentation link) for this case like in following example. Or you could use localStorage, but this does not work for local files (file:///...). And because of this window.name is better and shorter too.
Solution
function startGRBTimer(duration, display)
{
var timer = window.name == '' ? duration : window.name,
hours, minutes, seconds;
setInterval(function()
{
days = parseInt(timer / (24 * 60 * 60), 10);
hours = parseInt(timer % (24 * 60 * 60) / (60 * 60), 10);
minutes = parseInt(timer % (60 * 60) / 60, 10);
seconds = parseInt(timer % 60, 10);
hours = hours < 10 ? "0" + hours : hours;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = days + "d" + " " + hours + "h " + minutes + "m " + seconds + "s";
--timer;
if(timer <= 0)
{
timer = duration;
}
window.name = timer;
}, 1000);
}
var display = document.querySelector("#grb");
startGRBTimer(60, display);
<div id="grb"></div>

How to turn seconds (of one day) into text?

I have made this formula to turn a time as string into seconds (as integer)
seperated = new Date().split(":");
seconds = seperated[0] * 60 * 60 + seperated[1] * 60 + seperated[2];
How can I do this the reverse way?
I'm not very good at mathematics :)
EDIT:
I tried this: (the function makeTime(...) works)
function makeTime(timestr) {
var seperated = timestr.split(":");
return seperated[0] * 60 * 60 + seperated[1] * 60 + seperated[2];
}
function timeStr(integ) {
var hours = integ / 3600;
var minutes = (integ % 3600) / 60;
var seconds = integ % 60;
return hours + ":" + minutes + ":" + seconds;
}
Assuming time is the number of seconds as an integer:
hours = Math.floor(time/3600)
minutes = Math.floor((time % 3600) / 60)
seconds = time % 60
timeString = hours + ':' + minutes + ':' + seconds
You can use datejs, and write a code some thing like follows
(new Date).clearTime()
.addSeconds(15457)
.toString('H:mm:ss');
EDIT:
Or
hours = totalSeconds / 3600;
totalSeconds %= 3600;
minutes = totalSeconds / 60;
seconds = totalSeconds % 60;

Categories

Resources