get date/time off server not local machine - javascript

I've got this code to show a countdown message between Monday - Wednesday until Wednesday noon, then it disappears.
This is the code:
<script>
var today = new Date(),
curDay = today.getDay();
var deadline = new Date(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate() + 3 - curDay, 10, 59, 59));
function time_remaining(endtime){
var t = endtime - new Date();
var seconds = Math.floor( (t/1000) % 60 );
var minutes = Math.floor( (t/1000/60) % 60 );
var hours = Math.floor( (t/(1000*60*60)) % 24 );
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {'total':t, 'days': days, 'hours':hours, 'minutes':minutes, 'seconds':seconds};
}
function run_clock(id,endtime){
var clock = document.getElementById(id);
if (null === clock) {
return;
}
var days_span = clock.querySelector('.days');
var hours_span = clock.querySelector('.hours');
var minutes_span = clock.querySelector('.minutes');
var seconds_span = clock.querySelector('.seconds');
function update_clock(){
var t = time_remaining(endtime);
days_span.innerHTML = ('0' + t.days).slice(-2);
hours_span.innerHTML = ('0' + t.hours).slice(-2);
minutes_span.innerHTML = ('0' + t.minutes).slice(-2);
seconds_span.innerHTML = ('0' + t.seconds).slice(-2);
day = today.getDay();
if((t.total<=0) || (day === 0) || (day === 6) || (day === 5) || (day === 4)){
clearInterval(timeinterval);
document.getElementById('deadline_Container').style.display = "none";
}
}
update_clock();
var timeinterval = setInterval(update_clock, 1000);
}
if (curDay > 0 && today < deadline) {
run_clock('clockdiv', deadline);
}
</script>
Now this works fine, however if somebody is in a different time zone for example the timings of the countdown won't be right. So I was wondering if there is any way to run this off the server time rather than the local time of the machine the user is using?

Related

JavaScript countdown timer for every Monday, Wednesday and Friday at 2000 hrs

I am trying to create a countdown timer for every Monday, Wednesday and Friday at 2000 hours in JavaScript.
Countdown is working till 2000 hours but after that its not working and also I can't figure out how to switch week i.e. Friday to switch next Monday as there are 3 days count and normal in week there are two days and also I don't want to show days.
I want to convert days into hours and my UI is like 47h 59m 50s this.
I would be grateful if anyone can figure out how to create this countdown.
const gameCountdown = setInterval(function() {
var gameDay;
var currentDateTime = new Date();
var currentDay = currentDateTime.getDay();
var currentTime = currentDateTime.getTime();
var gameTime = new Date(currentDateTime.getFullYear(), currentDateTime.getMonth(), currentDateTime.getDate(), 20, 0, 0); // current day 8pm
var gameDay = (currentDay % 2 === 0) ? currentDay + 1 : currentDay;
if ((currentDay === gameDay) && (gameTime.getHours() >= 20)) {
gameTime = currentDateTime.setDate(currentDateTime.getDate() + 2);
}
var countdownTime = gameTime.getTime();
var difference = parseInt((countdownTime - currentTime));
if (difference > 0) {
var hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
var mins = Math.floor((difference / (1000 * 60)) % 60);
var sec = Math.floor((difference / 1000) % 60);
document.querySelector('#hours').innerHTML = hours + 'h';
document.querySelector('#min').innerHTML = mins + 'm';
document.querySelector('#sec').innerHTML = sec + 's';
} else {
var hours = Math.floor((difference / (1000 * 60 * 60)) % 24);
var mins = Math.floor((difference / (1000 * 60)) % 60);
var sec = Math.floor((difference / 1000) % 60);
document.querySelector('#hours').innerHTML = hours + 'h';
document.querySelector('#min').innerHTML = mins + 'm';
document.querySelector('#sec').innerHTML = sec + 's';
}
}, 1000);
<span id="hours"></span>
<span id="min"></span>
<span id="sec"></span>
Does this work for you?
const getGameTime = (currentTime) => {
let gameDate = new Date(currentTime)
let offset = 0;
if (gameDate.getHours() >= 20) {
offset += gameDay === 5 ? 3 : // Friday after 20:00
1; // any other day
}
gameDate.setDate(gameDate.getDate() + offset);
let gameDay = gameDate.getDay();
offset = 0;
if (gameDay === 0) offset += 1; // Sunday
else if (gameDay === 2 || gameDay === 4) offset += 1; // Tuesday or Thursday
else if (gameDay === 6) offset += 2; // Saturday
gameDate.setDate(gameDate.getDate() + offset);
gameDate.setHours(20, 0, 0);
return gameDate.getTime();
}
const gameCountdown = setInterval(function() {
var gameDay;
var currentDateTime = new Date();
var currentDay = currentDateTime.getDay();
var currentTime = currentDateTime.getTime();
var countdownTime = getGameTime(currentTime);
var difference = parseInt((countdownTime - currentTime));
var hours = Math.floor((difference / (1000 * 60 * 60)));
var mins = Math.floor((difference / (1000 * 60)) % 60);
var sec = Math.floor((difference / 1000) % 60);
document.querySelector('#hours').innerHTML = hours + 'h';
document.querySelector('#min').innerHTML = mins + 'm';
document.querySelector('#sec').innerHTML = sec + 's';
}, 1000);
<span id="hours"></span>
<span id="min"></span>
<span id="sec"></span>

Setting a countdown that does something in the end

I'm trying to set a countdown that will do something before and after,
I'm using the code from this site: https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/
I have this code, but I don't know how to:
set the end time;
do something before and after the timer is done;
schedule the clock automatically.
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
//var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
var schedule = [
['May 10 2020', 'May 10 2020']
];
//initializeClock('clockdiv', deadline);
// iterate over each element in the schedule
for(var i=0; i<schedule.length; i++){
var startDate = schedule[i][0];
var endDate = schedule[i][1];
// put dates in milliseconds for easy comparisons
var startMs = Date.parse(startDate);
var endMs = Date.parse(endDate);
var currentMs = Date.parse(new Date());
// if current date is between start and end dates, display clock
if(endMs > currentMs && currentMs >= startMs ){
initializeClock('clockdiv', endDate);
}
}
Could you please advise me?

set countdown to only show between monday and wednesday

I've currently got a countdown that counts to 11.59 am every day.
However, I need to set it so it counts down to Wednesday 11.59pm every week and only show from Monday.
So on Sunday, Saturday, Friday and Thursday the countdown won't show. I've figured that bit out but can't find a way to set my countdown for every Wednesday at 11.59pm.
I guess it would be done with getDay() somehow, but not sure how to put it together.
This is the code I've currently got:
var today = new Date(new Date().getTime());
var deadline = new Date(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate(), 10, 59, 59));
function time_remaining(endtime) {
var t = endtime - new Date();
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
return {
'total': t,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function run_clock(id, endtime) {
var clock = document.getElementById(id);
if (null === clock) {
return;
}
var hours_span = clock.querySelector('.hours');
var minutes_span = clock.querySelector('.minutes');
var seconds_span = clock.querySelector('.seconds');
function update_clock() {
var t = time_remaining(endtime);
hours_span.innerHTML = ('0' + t.hours).slice(-2);
minutes_span.innerHTML = ('0' + t.minutes).slice(-2);
seconds_span.innerHTML = ('0' + t.seconds).slice(-2);
day = today.getDay();
if ((t.total <= 0) || (day === 0) || (day === 6) || (day === 5) || (day === 4)) {
clearInterval(timeinterval);
document.getElementById('deadline_Container').style.display = "none";
}
}
update_clock();
var timeinterval = setInterval(update_clock, 1000);
}
run_clock('clockdiv', deadline);
You can use the getDay() value to get the current day(0(Sunday)...6(Saturday)), then use that to show the calendar and find the dead line
var today = new Date(),
curDay = today.getDay();
var deadline = new Date(Date.UTC(today.getFullYear(), today.getMonth(), today.getDate() + 3 - curDay, 10, 59, 59));
//var x = 0;
function time_remaining(endtime) {
var t = endtime - new Date();
//var t = endtime - new Date(today).setSeconds(today.getSeconds()+ ++x);
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
//console.log(t, days)
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function run_clock(id, endtime) {
var clock = document.getElementById(id);
if (null === clock) {
return;
}
var days_span = clock.querySelector('.days');
var hours_span = clock.querySelector('.hours');
var minutes_span = clock.querySelector('.minutes');
var seconds_span = clock.querySelector('.seconds');
function update_clock() {
var t = time_remaining(endtime);
days_span.innerHTML = ('0' + t.days).slice(-2);
hours_span.innerHTML = ('0' + t.hours).slice(-2);
minutes_span.innerHTML = ('0' + t.minutes).slice(-2);
seconds_span.innerHTML = ('0' + t.seconds).slice(-2);
day = today.getDay();
if ((t.total <= 0) || (day === 0) || (day === 6) || (day === 5) || (day === 4)) {
clearInterval(timeinterval);
document.getElementById('deadline_Container').style.display = "none";
}
}
update_clock();
var timeinterval = setInterval(update_clock, 1000);
}
if (curDay > 0 && today < deadline) {
run_clock('clockdiv', deadline);
}
<div id="deadline_Container"></div>
<div id="clockdiv">
<span class="days"></span>
<span class="hours"></span>
<span class="minutes"></span>
<span class="seconds"></span>
</div>

How to build a javascript countdown timer that doesn't reset on page refresh?

I found this code from this site: https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies. This code gives a countdown timer that resets on page refresh.
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
Later on the article the author says to implement the below code to the above code to get a timer that won't reset on page refresh. Since I'm a beginner, I could not implement the code properly. so can you please help me to do it properly. Thanks.
Here's the code and the instruction author gave:
Maintain Clock Progress across Pages
Sometimes it’s necessary to preserve the state of the clock for more than just the current page. For example, if we wanted a ten minute countdown across the site, we wouldn’t want the clock to reset every time the user goes to a different page or every time the user refreshes the page they are on.
One solution is to save the clock’s end time in a cookie. That way, navigating to a new page won’t reset the end time to ten minutes from now.
Here’s the logic:
If a deadline was recorded in a cookie, use that deadline.
If the cookie isn’t present, set a new deadline and store it in a cookie.
To implement this, replace the deadline variable with the following:
// if there's a cookie with the name myClock, use that value as the deadline
if(document.cookie && document.cookie.match('myClock')){
// get deadline value from cookie
var deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
}
// otherwise, set a deadline 10 minutes from now and
// save it in a cookie with that name
else{
// create deadline 10 minutes from now
var timeInMinutes = 10;
var currentTime = Date.parse(new Date());
var deadline = new Date(currentTime + timeInMinutes*60*1000);
// store deadline in cookie for future reference
document.cookie = 'myClock=' + deadline + '; path=/;
domain=.yourdomain.com';
}
Here is code (although I don't recommend learning programming by just copy/pasting):
<html>
<head>
<title>Timer</title>
<script>
var timeoutHandle;
function countdown(minutes,stat) {
var seconds = 60;
var mins = minutes;
if(getCookie("minutes")&&getCookie("seconds")&&stat)
{
var seconds = getCookie("seconds");
var mins = getCookie("minutes");
}
function tick() {
var counter = document.getElementById("timer");
setCookie("minutes",mins,10)
setCookie("seconds",seconds,10)
var current_minutes = mins-1
seconds--;
counter.innerHTML =
current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
//save the time in cookie
if( seconds > 0 ) {
timeoutHandle=setTimeout(tick, 1000);
} else {
if(mins > 1){
setTimeout(function () { countdown(parseInt(mins)-1,false); }, 1000);
}
}
}
tick();
}
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
window.onload = function startingTimer(){
//countdown(prompt("Enter how many minutes you want to count down:"),true);
countdown(2,true);
}
</script>
</head>
<body>
<div id="timer">00:00:00</div>
</body>
</html>
Note: This code is not mine, I took it from here and edited it a little bit for your needs.

Javascript Countdown to show/hide on specified days & hours

Hi I've been trying to take and work with some code that I can get partially working, I want a countdown that we can set an end time it counts down to (obvious is obvious out of the way), we also want to set it to show at only certain times of the day and only certain days of the week.
I've managed to get the below working so we can set a time of the day to show but I can't get it to work so it only shows on the certain specified days. Can anyone help please?
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
if (d.getHours() >= 7 && d.getHours() <= 15) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>
[EDIT]
Just to add to this I tried changing part of the script to this but it didn't work:
$(function() {
$("#countdown").datepicker(
{ beforeShowDay: function(day) {
var day = day.getDay();
if (day == 1 || day == 2) {
//gets the current time.
var d = new Date();
if(d.getHours() >= 7 && d.getHours() <= 10 ){
$("#countdown").show();
}
else {
$("#countdown").hide();
}
} else {
$("#countdown").hide();
}
}
});
});
Whatever you did is all good except the setInterval part where you are passing the string value as setInterval("tick()", 1000) instead of a function reference as setInterval(tick, 1000)
Also, I have updated the code as below to check the specific day along with specific hours which you had,
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
} else {
$("#countdown").hide();
}
}
You can give a try below,
var countdownMessage = "This ends in";
var now = new Date();
var time = now.getTime(); // time now in milliseconds
var countdownEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 12, 59); // countdownEnd 0000 hrs
//////////////////////////* Countdown *///////////////////////////////
function getSeconds() {
var ft = countdownEnd.getTime() + 86400000; // add one day
var diff = ft - time;
diff = parseInt(diff / 1000);
if (diff > 86400) {
diff = diff - 86400
}
startTimer(diff);
}
var timeInSecs;
var ticker;
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval(tick, 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
//getSeconds(); // and start again if required
}
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
var result = ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = (countdownMessage) + " " + result;
}
$("#countdown").hide();
///////////////* Display at certain time of the day *//////////////////
//gets the current time.
var d = new Date();
var day = d.getDay();
if (day == 0 || day == 6) {
if (d.getHours() >= 0 && d.getHours() <= 8) {
$("#countdown").show();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="getSeconds()">
<span id="countdown" style="font-weight: bold;"></span>
</body>

Categories