Count up Timer changes for text output - javascript

I'm a real JS novice. I finally found a simple webpage-only script that gives a count up time from a fixed date, and with beginner's luck I tweaked it to give text output in minutes and hours from the supplied span html.
However it shows "Updated 0 hours 9 min ago".
I want to remove the unnecessary '0 hours' until 60 minutes have passed to show: "Updated 9 min ago".
Then show hours again: "Updated 1 hours 1 min ago".
Appreciate any help on this, many thanks.
window.onload = function() {
// Month Day, Year Hour:Minute:Second, id-of-element-container
countUpFromTime("Jan 22, 2020 08:45:30", 'countup1'); // ****** Change this line!
};
function countUpFromTime(countFrom, id) {
countFrom = new Date(countFrom).getTime();
var now = new Date(),
countFrom = new Date(countFrom),
timeDifference = (now - countFrom);
var secondsInADay = 60 * 60 * 1000 * 24,
secondsInAHour = 60 * 60 * 1000;
days = Math.floor(timeDifference / (secondsInADay) * 1);
hours = Math.floor((timeDifference % (secondsInADay)) / (secondsInAHour) * 1);
mins = Math.floor(((timeDifference % (secondsInADay)) % (secondsInAHour)) / (60 * 1000) * 1);
secs = Math.floor((((timeDifference % (secondsInADay)) % (secondsInAHour)) % (60 * 1000)) / 1000 * 1);
var idEl = document.getElementById(id);
idEl.getElementsByClassName('hours')[0].innerHTML = hours;
idEl.getElementsByClassName('minutes')[0].innerHTML = mins;
clearTimeout(countUpFromTime.interval);
countUpFromTime.interval = setTimeout(function(){ countUpFromTime(countFrom, id); }, 1000);
}

Related

Restart counter every week

I would like to create a counter that reset every week, I found a code that more or less works, but when It goes to 0, it appears negative.... -1d -1h -2m -5s
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 29, 2021 20:21:0").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 an 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);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
//document.getElementById("demo").innerHTML = "GAME DAY";
if(distance < - 1000 * 60 * 60* 24){ // if its past the "game day"
// reset timer to next week
countDownDate += 1000 * 60 * 60 * 24 * 7
}
}
}, 1000);
</script>
<span id="demo"></span>
Instead of hard-coding the date, you need to calculate the next date based on the current date.
Something like this, though you'd be better of moving the magic numbers (5 and 20) into variables.
let getNextGameDayTime = function() {
let now = new Date();
let dayOfTheWeek = now.getDay();
let dayOffset = 5 - dayOfTheWeek; // Friday is the 5th day of the week
if (dayOffset < 0 || (dayOffset === 0 && now.getHours() > 20)) {
dayOffset += 7;
}
let result = new Date();
result.setDate(result.getDate() + dayOffset);
result.setHours(20);
result.setMinutes(0);
result.setSeconds(0);
result.setMilliseconds(0);
return result;
}
console.log(getNextGameDayTime());
As for not displaying the message for the hour after a countdown has finished, you could use the resulting distance for this.

How to make countdown start every eight hours?

I wonder how to make countdown start every 8 hours? for example
the puzzle starts at 10 pm next is 6 am, and next 2 pm.
I have javascript like this
<script>
var countDownDate = new Date("May 31 2020 22:00:00");
var now = new Date();
if (now.getHours() < countDownDate.getHours()) {
countDownDate = countDownDate;
} else
if (countDownDate.getHours() <= now.getHours()) {
countDownDate.setDate(countDownDate.getDate() + 1);
}
var x = setInterval(function() {
var now = new 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 and start new countdown
if (distance < 0) {
clearInterval(x);
}
}, 1000);
</script>
and how to make that countDown date every 8 hours? like 10 pm, 6 am and 2 pm? Thank you.
How about wrapping it in a function that takes in a date (in ms, in this case) (countdown(date)) and then calling the function with 8+ hours once the timer is up:
// Set the date we're counting down to
var countDownDate = new Date("May 31, 2020 22:00:00").getTime();
function countdown(date) {
// 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 = date - 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 and start new countdown
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
let newDate = date + (8 * 3600 * 1000);
countdown(newDate);
}
}, 1000);
}
countdown(countDownDate);
DEMO using initial countdown set to 3 seconds from now.
Code Explanation:
take in the initial date - can be set to anything.
Countdown until the initial date is reached.
Start a new 8-hour timer.
Example case starting date = "May 31, 2020 19:37:35".
First countdown will countdown 5 hours (from now to 19:37:35).
Second countdown will countdown 8 hours (from 19:37:35 until
03:37:35).
Third countdown will countdown 8 hours (from 3:37:35 to 11:37:35).
Try to evaluate the starting countdown time by current time, then set the start of countdown time to that time.
Something like:
var countDownDate = new Date("May 31, 2020 22:00:00");
var currentHour = countDownDate.getHours();
// 10 pm to 6 am
if(currentHour >= 22 && currentHour < 6) {
// set countdown startTime to 10 pm
countDownDate.setHours(22);
}
// 6 am to 2 pm
else if(currentHour >= 6 && currentHour < 14) {
// set countdown startTime to 6 am
countDownDate.setHours(6);
} else {
// set countdown startTime to 2 pm
countDownDate.setHours(14);
}

How to set a timer that keeps extending itself

I have build a popup with a timer. When the timer ends I want it to extend itself with another day. I have gone so far that it extends itself with 1 day for 1 time but then it quits.
Maybe you have any idea on how to proceed?
Thanks!
//Make countdown
var setInfiniteTime = '{{ $actiepopup->infiniteTime }}';
// Update the count down every 1 second
var x = setInterval(function() {
// Set the date we're counting down to
// Get todays date and time
var currentDate = new Date().getTime();
// get countdown time
var countDownDate = new Date(countDownTimeUntil).getTime();
// console.log('countdowndateBefore' + countDownDate);
// check in infinite time is set
if (setInfiniteTime == 'Yes') {
if (currentDate >= countDownDate) {
// var i;
// for (var i = 0; i < 999999; i++) {
var countDownDate = new Date(countDownTimeUntil).getTime() + 86400000;
// console.log(i);
// }
}
}
// console.log('currentdate' + currentDate);
// console.log('countdowndate' + countDownDate);
// Find the distance between now and the count down date
var distance = countDownDate - currentDate;
// 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);
// Display the result in the element with id="countdown"
$("#countdown").text(days + "d " + hours + "h " + minutes + "m " + seconds + "s ");
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
$("#countdown").text("Actie beeïndigd");
}
}, delayInMilliseconds);
Hope you have enough information!
SetInterval()
Also, just an advice, if you use boolean statements, just use true or false since it's way easier to work with
if (setInfiniteTime) {
setInterval(() => {
var countDownDate = new Date(countDownTimeUntil).getTime() + 86400000
}, 86400000)
}

jQuery/Javascript Calculate Difference beetween two dates in months, weeks, days, hours, minutes and seconds

I want to calculate the difference beetween two dates in Javascript in months, weeks, days, hours, minutes and seconds.
Problem:
Weeks and days aren't calculated properly.
I already tried to change .get...() into .getUTC...() but the difference was calculated wrong either.
var date = new Date("{% if holiday.is_now %}{{ holiday.end_date.isoformat }}{% else %}{{ holiday.end_date.isoformat }}{% endif %}");
function calcDate(a, b) {
var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDay(), a.getHours(), a.getMinutes(), a.getSeconds());
var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDay(), b.getHours(), b.getMinutes(), b.getSeconds());
return (utc2 - utc1) / 1000;
}
function convertDate(seconds){
var sec = Math.floor(seconds % 60);
var min = Math.floor(seconds / 60 % 60);
var hour = Math.floor(seconds / 60 / 60 % 24);
var diff = seconds / 60 / 60 / 24;
var months = Math.floor(diff / 30);
var weeks = Math.floor(diff / 7 % (30 / 7));
var days = Math.floor(diff % 7);
console.log(days);
return [months, weeks, days, hour, min, sec]
}
function add_countdown(sec){
$.each(convertDate(sec), function(i, element){
var selected = $("footer .countdown .counter#_counter_date_" + i);
selected.find("h1").text(element);
singular_pluralize(selected.find("p"), element);
})
}
function singular_pluralize(element, integer){
integer > 1 || integer == 0 ? element.text(element.attr("data-word-plural")) : element.text(element.attr("data-word-singular"));
}
var interval;
$("footer table td.a").on("click mouseup", function(){
clearInterval(interval);
date = new Date($(this).attr("data-date"));
$("footer #_foter_big_countdown_to_what").text("zu den " + $(this).attr("data-name").replace(/ /g, ''));
set_interval();
})
function set_interval(){
add_countdown(calcDate(new Date(), date));
interval = window.setInterval(function(){
var calc = calcDate(new Date(), date);
if (calc == 0)
holiday_begin();
else
add_countdown(calc);
}, 900);
}
function holiday_begin(){
$("footer .counter, footer .part#_footer_select_holiday").remove();
$("footer .darken h1._footer_big_countdown").html("Fröhliche Ferien!");
}
set_interval();
EDIT:
I found the solution. I had to use Math.round and I had to change a little bit:
function convertDate(seconds){
var sec = Math.round(seconds % 60);
var min = Math.round(seconds / 60 % 60);
var hour = Math.round(seconds / 60 / 60 % 24);
var diff = seconds / 60 / 60 / 24;
var months = Math.round(diff / 30);
var days = Math.round(diff % 30);
var weeks = Math.round(months / 4.3);
return [months, weeks, days, hour, min, sec]
}

create a countdown that the remain time is equal no mather the country

i can image someone had donde this already or it can be considered a duplicated question, i've been searching for weeks and i can't figure out how to accomplish this.
I have a countdown made in js, the problem i'm facing is that when ever i test it in another country the times throw out different hours example.
i'm in centralamerica, end date is apr 16, 2018 23:59:59" if i test this in centralamerica it says 6 days and 10 hours remaining, if i run this in italy for example it says 6 days and 3 hours remaining, i need it to be equal all the time and that the timezone doesn´t affects, is this even possible, and please help on how to get it done.
the script i have is working but not the way i need to, i have a promo that will expire on "apr 16, 2018 23:59:59" so if it only has 5 hours remaining it shout say 5 hours remaining no matter where its been seeing from, but that is not happening.
$("#masterslider").append("<p id='demo'>.</p>")
$("#masterslider").append("<span> remaining time </span>")
//******************************** update date here ************************
var serverDate = new Date("apr 16, 2018 23:59:59");
var offset = serverDate.getTimezoneOffset();
serverDate = addOffset(serverDate, offset);
setInterval(function(){
updateCountdown();
}, 1000);
function addOffset(date, offset) {
var time = date.getTime() ;
return new Date(time + offset * 6000);
}
function updateCountdown() {
var userDate = new Date();
var distance = serverDate.getTime() - userDate.getTime();
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);
if(serverDate.getTime() > userDate.getTime()){
$('#demo').html( days +"day(s)"+ " / " + hours + "hour(s)" + minutes + "minutes(s)");
}
else
{
$("#demo").html(mas);
$("#masterslider span").hide();
}
}
</script>
I've checked and setting correct timezone for "event timestamp" works for me regardless local client timezone I use.
let targetDate = new Date("2018-04-11 23:59:59 GMT-0800");
let refreshDelayMs = 1000;
function updateCounter() {
let distance = (targetDate - new Date()) / 1000;
let seconds = Math.floor(distance % 60).toString().padStart(2, '0');
distance = distance / 60;
let minutes = Math.floor(distance % 60).toString().padStart(2, '0');
distance = distance / 60;
let hours = Math.floor(distance % 24).toString().padStart(2, '0');
let days = Math.floor(distance / 24).toString().padStart(2, '0');
document.querySelector('.counter').innerHTML = `${days} days ${hours}:${minutes}:${seconds}`;
setTimeout(updateCounter, refreshDelayMs);
}
updateCounter();
Remains: <span class="counter"></span>
You can use moment-timezone from CDN or use NPM
repl.it sample
const moment = require("moment-timezone");
function toTimeZone(time, offset) {
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
return moment(time, format).utcOffset(offset).format(format);
}
toTimeZone("2018/04/10 15:37", "+0730")

Categories