On our site we're trying to execute a script that counts down to midnight everyday, displays a message, and then "resets" at midnight.
The message is basically "Order within X1, Get By X2"
The script calculates X1 to be XX Hours XX Minutes until midnight. X2 is 5 days, after today (if today is the 1st, it would be the 2nd + 5 giving you the 7th, with the exception of Sunday, then it will automatically skip to the Monday immediately after).
The problem though is that for some reason this script refuses to load for the front-end user, yet as a logged in admin I can see the code.
<!-- Allows to add estimated delivery time to the product and/or cart page -->
<div class="dailytimer"><strong>Order within <span id='mycountdown' style="color: #FF0000;"></span>, Get it by <span id="delDate" style="color: #FF0000;"></span></strong></div>
<script>
// First part of output
var myreset = [00,00,00]; // at what time to reset - 19:40:00
// Added myCountDownDiv variable to prevent jquery from walking the DOM o every update
var myCountDownDiv = document.getElementById('mycountdown');
var mycountdown = startCountdown();
function startCountdown(){
var enddate = calculateEndDate();
return setInterval(function(){tickTock(calculateStartDate(),enddate)}, 1000);
}
function calculateStartDate(){ //this needs to be edited if using the server time
return new Date();
}
function calculateEndDate(){
var enddate = new Date();
enddate.setHours(myreset[0]);
enddate.setMinutes(myreset[1]);
enddate.setSeconds(myreset[2]);
return enddate;
}
function tickTock(startdate, enddate){
var diff = enddate.getTime() - startdate.getTime();
d = diff >= 0 ? diff : diff + 24*3600*1000;
var h = Math.floor(d / 3600 / 1000);
var m = Math.floor(d / 60 / 1000) - 60*h;
var s = Math.floor(d / 1000) - 3600*h - 60*m;
printCountdown(h,m,s);
}
function pluralize(word,count){
return (count > 1) ? word+'s ' : word+' ';
}
function printCountdown(h,m,s){
// Updated string concatination. 'and' was deisplayed after the seconds value
var t = h + pluralize(' hour',h)+ m+pluralize(' minute',m);
myCountDownDiv.innerText = t;
// Removed jquery
//$('#mycountdown').html(t);
}
var fromDate = new Date();
fromDate.setDate(fromDate.getDate() + 6);
if (fromDate.is().saturday() || fromDate.is().sunday()) {
fromDate = fromDate.next().monday();
}
document.getElementById('delDate').innerHTML = fromDate.toString('ddd MMMM dS');
</script>
It's using a date JS file I found online to calculate the dates. I'm also pretty sure there's a better way for us to "insert" the code into the page without literally coping it into a html widget inside of elementor (we're using it as a page builder) but I just haven't really thought of one off hand.
Any help would be greatly appreciated as I'm about 5 steps from wanting to just hit delete on the whole thing haha
Related
I have several web pages that use " " as a placeholder for javascript function output to display a button label. For example, the following is the html that displays the output if the 'clock()' function,
<div id="clock" class="sidebar"> </div>
This one displays 'Login' until the 'log()' function is called, then changes the label to 'Logout',
<div id="login" class="sidebar"> </div>
The javascript references the IDs to direct the output to the labels. Both of these were working until a few days ago, but now are just blank. No label is displayed. Nothing obvious has changed. No updates to the system, etc. The server is running Ubuntu 16.04 lts and apache2 web server.
I have no idea why these would just quit working or where to begin looking for the problem. I have similar code running on a separate server that still works. Are there any workarounds / alternative methods that would produce the output I want?
edit:
Here is the javascript as requested:
function clock() {
var time = new Date(); //get the date
//find what day of the year it is
var start = new Date(time.getFullYear(), 0, 0);
var day = Math.floor((time - start) / (1000 * 60 * 60 * 24));
var offset = time.getTimezoneOffset() / 60;
if ((time.getHours() + offset) > 23) { day + 1; }
//get the fraction part of the day
var hour = time.getUTCHours() / 24;
var minute = time.getUTCMinutes() / 1440;
var sec = time.getUTCSeconds() / 86400;
var fraction = hour + minute + sec;
//display
$('#clock a').html((day + fraction).toFixed(4));
//change clock fontsize to fit well
var width = $('#clock').css('width');
var size = parseInt(width) / 4.75;
size = size + 'px';
$('#clock').css({'font-size':size});
}
/*makes either a login popout or logs someone out*/
function log() {
if ($('#login').html() == "Login") {
window.open("./login.html", "_blank","width=1000,height=500");
}
else { logout(); }
}
I need some advice and logic in my problem.
So, I have an entrydate, from database, then the running current date, and a value of 10(double type in database). So, I know how to calculate the diff of the entrydate and current date, right. So I convert it to seconds then to a number(9.23165).
|Entry |Current Date|Diff(in number)|
|2:00:00 PM |2:30:00 PM | 5.00(Sample)|(First User)
So basically, as current date goes on, can PHP show the deduction on real time? Or I need to refresh? What I need is for it to display the deduction without refreshing. So basically, I need to know what I have to do. Maybe javascipt and ajax?
What you would need are a few Javascript/jQuery functions to update the browser in real time.
var myTimer;
var startTime;
function startTimer() {
stopTimer(); // Reset
startTime = new Date(); // Save to calculate difference
myTimer = setInterval(clockTicking, 1000);
}
function stopTimer() {
clearInterval(myTimer);
}
function clockTicking() {
var now = new Date();
var timeDiff = new Date(now - startTime); // constructor uses UTC, so use UTC date functions from here on
var hours = (timeDiff.getUTCHours() < 10) ? '0' + timeDiff.getUTCHours() : timeDiff.getUTCHours();
var mins = (timeDiff.getUTCMinutes() < 10) ? '0' + timeDiff.getUTCMinutes() : timeDiff.getUTCMinutes();
var secs = (timeDiff.getUTCSeconds() < 10) ? '0' + timeDiff.getUTCSeconds() : timeDiff.getUTCSeconds();
$("<element-where-you-display>").html(hours + ':' + mins + ':' + secs);
}
In Javascript you can call startTimer() to kick it off.
The following code is a countdown timer. It pulls an ending datetime stamp from mySQL and uses it to count to. The issue is that the mysql time may be in a different time zone than the client who is looking at the page with the timer.
I also pull the current timestamp from mySQL with NOW(), thinking that this would allow the timer to count as the user who created it intended.
if I put the NOW() value in this snippet
var timeDiff = target - (new Date());
like so
var nt='2015-03-11 05:12:15'.split(/[- :]/);
var timeDiff = target - (new Date(nt[0],nt[1]-1,nt[2],nt[3],nt[4],nt[5]));
the counter shows the correct time left when the page loads but does not count interactively any longer. I think I need to get the difference in hours between the clients local time and the mySQL NOW() and adjust the date in this line to get the interactive timer to run.
var timeDiff = target - (new Date());
nothing I try seems to work.
This is the working script if the client happens to be int he same time zone.
<script language="javaScript">
document.write(hrs);
function timeDiff(target) {
function z(n) {return (n<10? '0' : '') + n;}
var timeDiff = target - (new Date());
var hours = timeDiff / 3.6e6 | 0;
var minutes = timeDiff % 3.6e6 / 6e4 | 0;
var seconds = timeDiff % 6e4 / 1e3 | 0;
if (hours<0 || minutes<0 || seconds<0) {
document.getElementById('divBody').style.display='none';
document.getElementById('divExpired').style.display='';
return '<b>EXPIRED</b>';
}
else {
return '<b>' + z(hours) + '</b> Hours, <b>' + z(minutes) + '</b> Mins, <b>' + z(seconds) + '</b> Secs';
}
}
function doCountDown(target) {
document.getElementById('timer').innerHTML = '<img src=\"/backhaul/images/my/al-active.png\" class=\"vm2\" /> <span style=\"color:#c40000\"><b>EXPIRES IN</b></span>: ' + timeDiff(target);
var lag = 1020 - (new Date() % 100);
setTimeout(function(){doCountDown(target);}, lag);
}
window.onload = function() {
//Insert Expiratin Date from mySQL into t var
var t='2015-03-12 00:00:00'.split(/[- :]/);
doCountDown(new Date(t[0],t[1]-1,t[2],t[3],t[4],t[5]));
}
</script>
There are many ways of doing this, but I'll elaborate on two ways.
Method 1 : Adjust the time on the client side
One way is what you are trying to do which is to get the current time of the server and find the difference with the client's current time. You can simply adjust the server target time to the client's time. This can be done with
var serverDifference=Date.parse(mysql_data.now)-Date.now()
var target=Date.parse(mysql_data.server_time_in_two_hours)-serverDifference
Then you can input it into your function without problem.
Method 2: Calculate the times remaining, server side
Since you just need a countdown timer, I think it's more appropriate to simply send the seconds left server side. This can be done with SQL using
select timestampdiff(SECOND,now(),end_time) seconds_left from timers;
Then you simply just make a timer that counts down based on the number of seconds left instead of a target date. You can calculate the number of seconds left by deducting the time that the javascript has run from the time received from the server. So something like
var client_start=Date.now()
function timeDiff_fromseconds(target) {
function z(n) {return (n<10? '0' : '') + n;}
var timeDiff =target-(Date.now()-client_start)
var hours = timeDiff / 3.6e6 | 0;
var minutes = timeDiff % 3.6e6 / 6e4 | 0;
var seconds = timeDiff % 6e4 / 1e3 | 0;
if (hours<0 || minutes<0 || seconds<0) {
return '<b>EXPIRED</b>';
}
else {
return '<b>' + z(hours) + '</b> Hours, <b>' + z(minutes) + '</b> Mins, <b>' + z(seconds) + '</b> Secs';
}
}
There is also performance.now() as suggested by #dandavis. This returns the number of milliseconds since the tab opened and is accurate to 1/1000th of a millisecond. And this doesn't change even if the system clock of the client browser changes. For full support, you should use a polyfill (As of the time of this writing, iOS Safari doesn't support it). In this context we can replace Date.now() with it.
JSFiddle Demo:
http://jsfiddle.net/3o3u5r5j/1/
If it is possible to get remaining amount of seconds from database instead of expiry time (meaning to calculate it at the server and send to the client). Then you can use following code (sample). Fiddle
var countDownId;
var timer;
function countDown(){
console.log(timer--);
if(timer<=0){
clearInterval(countDownId);
alert('time expired');
}
}
function startCountDown(secondsToExpire){
var milliseconds = 1 * 1000 ;// 1 second
timer = secondsToExpire;
countDownId = setInterval(function() { countDown();},milliseconds);
}
window.onload = function() {
//Insert remaining time from expiration
var timeRemaining = 5;
startCountDown(timeRemaining);
}
You can tweak this to suit your needs.
I have had a good search for what I'm looking for but can't seem to find exactly what I need. I'm new to jQuery and JavaScript.
All I want to do is subtract one 24 hour clock time from another to find how many hours have been allocated using JQuery or JavaScript i.e. start time: 12:00 end time: 16:00 would be 4 hours.
How would I go about doing this without having issues when going from say 12:00 till 12:00 the following day?
I am not dealing with with dates, just time.
Currently the times are stored like this as part of an object with start_time end_time:
var shift = {'location':$('#shift_location').val(),
'shift_date': $('#shift_date').val(),
'start_time':$('#shift_start_time').val(),
'end_time':$('#shift_end_time').val()
};
var shift_list = JSON.parse(localStorage.shift);
shift_list.push(shift);
localStorage.shift = JSON.stringify(shift_list);
With the given information i.e start_time and end_time there is no way you can cover multiple days. They just oscillate between 0 to 23 hours. There is no counter involved to calculate multiple days. if you need that you need two more states which will store start_date and end_date which will act as counter as pointed by #John Boker. But if you are sure that the difference never goes beyond 24 hours then we can use the parseTime from JAVASCRIPT: subtracting Time and getting its number of minutes function with our own little modifications.
function parseTime(s) {
var c = s.split(':');
return parseInt(c[0]) * 60 + parseInt(c[1]);
}
var limit = parseTime("23:59");
function getDiff(start_time, end_time){
var a = parseTime(start_time), b = parseTime(end_time);
if(b < a) // means its the next day.
return Math.round((limit - a + b)/60);
else if(b > a)
return Math.round((b - a)/60);
else if(b - a == 0)
return 24.0;
else
alert("Invalid data");
}
alert(getDiff("12:00", "11:00"));
You can use momentjs to do things with dates in javascript.
Example (moment doc, fiddle):
var start_time = "12:00";
var end_time = "16:00";
var start = moment.duration(start_time, 'h');
var end = moment.duration(end_time, 'h');
alert(end.subtract(start).hours()); // 4
Of course, because of the simplicity of the task you could always use plain javascript:
var start_time = "12:00";
var end_time = "16:00";
alert(parseInt(end_time, 10) - parseInt(start_time, 10)); // 4
I have a website that I want to be reloaded at a certain time, like 3:35pm, not after a specific interval like 5min. How do I do that?
The following JavaScript snippet will allow you to refresh at a given time:
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
Then you can add a script tag to call the refreshAt() function.
refreshAt(15,35,0); //Will refresh the page at 3:35pm
Note that this code will refresh based on the client local time. If you want it to be at a specific time regardless of the client's timezone, you can replace get*() and set*() (except getTime()) on the time objects with their getUTC*() and setUTC*() equivalent in order to pin it to UTC.
<META HTTP-EQUIV="Refresh" CONTENT="5">
this will force page to reload every 5 seconds. Just calculate the correct interval and add it to content tag
I found this page with a similar question and used it to hack out a more specific answer that may be of use to some. For this project, we wanted to make sure that the page refreshed once a live event of global interest was about to go on, activating the player embed on the user's page (narrow use case, I know -- others might have a better use for it).
One challenge in the above answers was how to deal with time zone conversions, which was more of an issue for us because we wanted to make sure that the page refreshed at a specific day and time. To do this, I grabbed a UTC version of the target date and today's date, converted them to GMT, then set Andrew's timeout function to the difference between the two.
var target = new Date("January 28, 2011 13:25:00");
timeOffset = target.getTimezoneOffset() * 60000;
targetTime = target.getTime();
targetUTC = targetTime + timeOffset;
var today = new Date();
todayTime = today.getTime();
todayUTC = todayTime + timeOffset;
refreshTime = (targetUTC - todayUTC);
if (refreshTime > 1) {
setTimeout(function() { window.location.reload(true); }, refreshTime);
}
Basically, when the page is accessed, calculate how much time is remaining between the access time and the time you want to reload the page, and use that remaining time in the meta refresh header. Obviously this would need to be done in a CGI script or web application, or possibly with SSI (server-side includes); it won't work if all you have is a static HTML file.
Another alternative would be to use Javascript, but it won't work if the client has Javascript disabled.
This worked better for my purposes.
If you're able to use Jquery and MomentJs, you can do this:
(function () {
var $ = require('jquery');
var moment = require('moment');
function refreshPageAtTime(expiration, countdownElement) {
var now = moment.utc();
console.log('now', now);
var expirationMoment = moment.utc(expiration, 'YYYY-MM-DD kk:mm:ss');
console.log('target', expirationMoment);
var secondsUntilRefresh = expirationMoment.diff(now, 'seconds');//http://momentjs.com/docs/#/displaying/difference/
console.log('diff in seconds', secondsUntilRefresh);
if (secondsUntilRefresh > 1) {
setInterval(function () {
secondsUntilRefresh--;
console.log('seconds remaining', secondsUntilRefresh, 'seconds');
if (secondsUntilRefresh <= 10) {
countdownElement.html(secondsUntilRefresh + '...');
if (secondsUntilRefresh === 0) {
console.warn('Refreshing now at ' + moment.utc());
window.location.reload(true);
}
}
}, 1000 * 1);
}
}
$(document).ready(function () {
var expiration = $('form').attr('data-expiration');
console.log('expiration', expiration);
$('.btn-primary:submit').after('<div id="countdownToRefresh" style="display: inline-block; color: #999; padding: 10px;"></div>');
refreshPageAtTime(expiration, $('#countdownToRefresh'));
});
})();
Basically, there are many javascript codes out there that can refresh the page ever so minutes or something, you can edit them to refresh at hours too. Like this one:
//enter refresh time in "minutes:seconds" Minutes: 0 to Whatever
//Seconds should range from 0 to 59
var limit = "0:30";
if (document.images) {
var parselimit = limit.split(":");
parselimit = parselimit[0] * 60 + parselimit[1] * 1;
}
var beginrefresh = function () {
if (!document.images) return if (parselimit == 1) window.location.reload()
else {
parselimit -= 1;
curmin = Math.floor(parselimit / 60);
cursec = parselimit % 60;
if (curmin != 0) curtime = curmin + " minutes and " + cursec + " seconds left until page refresh!";
else curtime = cursec + " seconds left until page refresh!";
window.status = curtime;
setTimeout("beginrefresh()", 1000);
}
}
window.onload = beginrefresh;
(now just calculate the minutes and seconds you want it to refresh, like for example noon everyday if it were noon now:
var limit = "1440:00";
Now you could use this code except, most of them don't work with server time, And with the information you provided us, we really can't do anything more. Edit your question and tell us if you want it to be timed with the servers time, or something else.
I hope this help,you can set the exact time for refresh
var target = new Date("November 18, 2019 10:00:00");
timeOffset = target.getTimezoneOffset() * 60000;
targetTime = target.getTime();
targetUTC = targetTime + timeOffset;
var today = new Date();
todayTime = today.getTime();
todayUTC = todayTime + timeOffset;
refreshTime = (targetUTC - todayUTC);
if (refreshTime > 1) {
setTimeout(function() { window.location.reload(true); }, refreshTime);
}
if you using Flask you can set variable synchronized to network time. In the flash app
from datetime import *`
def syncRefresh():`
while (datetime.now().second % 10 !=0):`
continue`
return True`
and #app.route('/', methods =["GET"})
def table():
....
if syncRefresh():
refreshNow = True # refreshNow is the variable passed to the web page
and in the html page
{% if refreshNow %}
<meta http-equiv="refresh" content="1">
{% endif %}
refresh at a given minute and second → i.e. every hour at fixed time can be as follows:
<script type="text/javascript">
function refreshAt(minute, second) {
var date= new Date();
var hr = date.getHours();
var m = date.getMinutes();
var s = date.getSeconds();
if(m == minute && s == second)
{
window.location.reload(true);
}
setTimeout(function() { refreshAt(minute, second); },600);
};
</script>
Use this to refresh the page every 20 seconds.
<META HTTP-EQUIV="refresh" CONTENT="20">