How to get servers time - javascript

Okay so i need a countdown to the servers midnight because when the server reach midnight it will run a cronjob which is relevant to the users so they need to see how many hours that are left untill it is midnight on the server and not in their own timezone.
Sample page here
The date_default_timezone_get(); is europe/copenhagen
PHP
(The page the Ajax is requesting)
echo time() * 1000;
Javascript
(function () {
var test = document.getElementById("test");
var difference = document.getElementById("difference");
var serverMilli = document.getElementById("serverMilli");
var serverCountdown = document.getElementById("serverCountdown");
var machineMilli = document.getElementById("machineMilli");
var machineCountdown = document.getElementById("machineCountdown");
let serverTime;
var localTime;
var http = new XMLHttpRequest();
var url = "time.php";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
serverTime = this.responseText;
}
;
};
http.send();
function countDownServer() {
var now = new Date();
var localTime = now.getTime();
var currentDiff = serverTime - localTime;
var currentTest = serverTime - currentDiff;
var currentTime = currentTest;
var eventDate = new Date();
eventDate.setDate(now.getDate() + 1);
eventDate.setHours(24);
eventDate.setMinutes(0);
eventDate.setSeconds(0);
eventDate.setMilliseconds(0);
var eventTime = eventDate.getTime();
var remainingTime = eventTime - currentTime;
var sekunder = Math.floor(remainingTime / 1000);
var minutter = Math.floor(sekunder / 60);
var timer = Math.floor(minutter / 60);
sekunder %= 60;
minutter %= 60;
timer %= 24;
sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
minutter = (minutter < 10) ? "0" + minutter : minutter;
timer = (timer < 10) ? "0" + timer : timer;
var testServer = timer + ":" + minutter + ":" + sekunder;
serverCountdown.textContent = testServer;
setTimeout(countDownServer, 1000);
}
countDownServer();
})();
Everything "kinda" works... the problem is if i change the timezone on my computer it will display longer hours untill midnight than it really is on the server?
How is this possible when the timezone on server is europe/copenhagen and i use time() ? should it not use the servers timezone?

No as javascript executes in your browser, it will use the timezone of your computer.
You have to tell javascript which timezone you would like (if not your one)
I found this for you:
How to get Time of specific timezone using javascript?

The JavaScript Date object always uses the user's computer time. You can use a library like Moment Timezone to set a different timezone that can be calculated on the client.
Otherwise you can try and calculate the difference between the server time and local time, but it might be off by an hour a couple times per year due to differences in DST.

Related

Countdown midnight server with PHP, vanilla js and Ajax

Okay i am trying once again since last time my post got flagged as a duplicate of something entirely different than what i were asking so basically the quick stackof'ers who does this to vannilla/php questions ruined my post and i got no valid answers...
This is not a jQuery question...
This is not a Ajax response question...
(I even found my own post as googles 1st result when trying to find answers for my question)
Sample here
Basically i made a midnight countdown timer in Javascript which works perfectly...
I am trying to make it countdown to midnight of server and not the local machine, so i did a Ajax call where i echo getTime(); and i am trying to put this.responseText inside where i used now.getTime();
Javascript/Ajax
(function () {
var serverMilli = document.getElementById("serverMilli");
var serverCountdown = document.getElementById("serverCountdown");
var machineMilli = document.getElementById("machineMilli");
var machineCountdown = document.getElementById("machineCountdown");
let serverTime;
var http = new XMLHttpRequest();
var url = "time.php";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function () {
if (http.readyState === 4 && http.status === 200) {
serverTime = this.responseText;
serverMilli.textContent = this.responseText;
}
;
};
http.send();
function countDownServer() {
var now = new Date();
var currentTime = serverTime - now.getTime();
var eventDate = new Date();
eventDate.setDate(now.getDate() + 1);
eventDate.setHours(24);
eventDate.setMinutes(0);
eventDate.setSeconds(0);
eventDate.setMilliseconds(0);
var eventTime = eventDate.getTime();
var remainingTime = eventTime - currentTime;
var sekunder = Math.floor(remainingTime / 1000);
var minutter = Math.floor(sekunder / 60);
var timer = Math.floor(minutter / 60);
sekunder %= 60;
minutter %= 60;
timer %= 24;
sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
minutter = (minutter < 10) ? "0" + minutter : minutter;
timer = (timer < 10) ? "0" + timer : timer;
var testServer = timer + ":" + minutter + ":" + sekunder;
serverCountdown.textContent = testServer;
setTimeout(countDownServer, 1000);
}
countDownServer();
function countDownMachine() {
var now = new Date();
var currentTime = now.getTime();
machineMilli.textContent = currentTime;
var eventDate = new Date();
eventDate.setDate(now.getDate() + 1);
eventDate.setHours(24);
eventDate.setMinutes(0);
eventDate.setSeconds(0);
eventDate.setMilliseconds(0);
var eventTime = eventDate.getTime();
var remainingTime = eventTime - currentTime;
var sekunder = Math.floor(remainingTime / 1000);
var minutter = Math.floor(sekunder / 60);
var timer = Math.floor(minutter / 60);
sekunder %= 60;
minutter %= 60;
timer %= 24;
sekunder = (sekunder < 10) ? "0" + sekunder : sekunder;
minutter = (minutter < 10) ? "0" + minutter : minutter;
timer = (timer < 10) ? "0" + timer : timer;
var testMachine = timer + ":" + minutter + ":" + sekunder;
machineCountdown.textContent = testMachine;
setTimeout(countDownMachine, 1000);
}
countDownMachine();
})();
All i had to do was to do time() * 1000 because time() returns seconds and .getTime() returns milliseconds... waow cant believe i oversaw this and had so many problems, cant believe none from stf dident see this xD

Real Time decreasing value in php

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.

show server time including timezone offset

i have some difficulties showing the actual time of the server using php and js.
on the server-side i have following php code:
$date = new DateTime();
echo $date->getTimestamp();
on the client-side if have the following js code that changes the content of a div to display the current time:
flag = true;
timer = '';
function clock()
{
if ( flag ) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "backend/time_backend.php?action=serverTime", false);
xmlhttp.send();
var stamp = xmlhttp.responseText;
timer = stamp*1000;
}
var d = new Date(timer);
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
//hours = hours % 12;
//hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' + seconds;
document.getElementById("clock").innerHTML= strTime ;
flag = false;
timer = timer + 1000;
}
window.onload = function() {
setInterval(clock, 1000);
};
this works as long as the timezone of the server and mine are the same. but as soon as i change the timezone on the server, it doesn't work anymore. it still will show my local client time although the bash command date on the server shows the time in the right offset.
how do i fix this? i really need to show the server-local time.
You are sending in unix timestamp from PHP
must be probably using
echo date("Y-m-d H:i:s", time());
if you want to use the string for creating date object using JS.
Your JS code should be
function clock()
{
if ( flag ) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "backend/time_backend.php?action=serverTime", false);
xmlhttp.send();
var stamp = xmlhttp.responseText;
var timer = new Date(stamp);
}
var d = new Date(timer);
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
//hours = hours % 12;
//hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' + seconds;
document.getElementById("clock").innerHTML= strTime ;
flag = false;
timer = new Date(timer.getTime() + 1000);
}
You could use an ISO 8601 formatted date.
$date = date("c", time());
Will give you one.
ISO 8601 Data elements and interchange formats – Information
interchange – Representation of dates and times is an international
standard covering the exchange of date and time-related data. It was
issued by the International Organization for Standardization (ISO) and
was first published in 1988. The purpose of this standard is to
provide an unambiguous and well-defined method of representing dates
and times, so as to avoid misinterpretation of numeric representations
of dates and times, particularly when data are transferred between
countries with different conventions for writing numeric dates and
times.
You could then do Date.parse() in which will return a timestamp ;) then proceed as if you received a timestamp.
Date::getTimestamp always returns the Unix timestamp. Unix timestamp does not store time zone information.
Solution is to build the JavaScript Date object from the date information given by the server.
Note: The time will not go out of sync when server or the client changes time zones (i.e. DST). If avoiding requests to backend a more accurate solution would be to use a time zone library in JavaScript (e.g. timezone.js).
PHP:
$date = new DateTime;
echo json_encode(array(
'year' => (int) $date->format('Y'),
'month' => (int) $date->format('m'),
'day' => (int) $date->format('j'),
'hours' => (int) $date->format('H'),
'minutes' => (int) $date->format('i'),
'seconds' => (int) $date->format('s'),
));
JavaScript:
var date = null;
function updateTime() {
if (!date) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "backend/time_backend.php?action=serverTime", false);
xmlhttp.send();
var j = JSON.parse(xmlhttp.responseText);
date = new Date(
j['year'], j['month'],
j['day'], j['hours'],
j['minutes'], j['seconds']
);
return;
}
// Increment time by 1 second
date.setTime(date.getTime() + 1000);
}
function clock() {
updateTime();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
hours = hours % 12;
hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ':' + seconds;
document.getElementById('clock').innerHTML = strTime;
}
window.onload = function() {
setInterval(clock, 1000);
};

How do I use setInterval with my form to create an alarm clock?

I'm currently trying to learn JavaScript and I've decided to make things more interesting by actually creating something instead of endless reading & no practice. I'm currently trying to build an alarm clock.
Here's my code:
http://codepen.io/anon/pen/dCsax
function wakeup() {
window.location = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"
}
I need to create another function that uses setInterval to check every few seconds if the time set in that form is equal to the current time, and if it is, execute the wakeup function that plays Rick Astley - Never Gonna Give You Up.
I don't know how to write this piece of code. Could someone please help me out so I can see how it's done?
Thanks in advance.
For a pure JS solution (no libraries) you should read about Date object
I've forked your example on codepen like this:
function set_alarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
if ( t == 'PM' ) h+= 12;
var now = new Date();
var d = new Date();
d.setHours(h);
d.setMinutes(m);
d.setSeconds(0);
var delta = d.getTime() - now.getTime();
if (delta < 0) delta = -delta;
setTimeout(wakeup,delta);
}
This should give you a hint about what to do.
You can also try using one of the many libraries about dates, expecially moment.js
I added an id to your button, and on click set up the timer function as below:
<input id="scheduleTimer" type="button" value="Schedule alarm"></input>
function getTimeoutSec() {
var dt = new Date();
var currSecs = dt.getSeconds() + (60 * dt.getMinutes()) + (60 * 60 * dt.getHours());
var am_pm = document.getElementById('t').value;
var formHour = parseInt(document.getElementById('h').value);
if(am_pm == 'PM') {
formHour += 12;
}
var formMin = parseInt(document.getElementById('m').value);
var formSeconds = (formHour * 3600) + (formMin * 60);
return formSeconds - currSecs;
}
window.onload = function() {
var scheduleTimerButton = document.getElementById('scheduleTimer');
scheduleTimerButton.addEventListener('click', function() {
var secRemaining = getTimeoutSec();
setTimeout(wakeup, secRemaining * 1000);
}, false);
};
Link to CodePen
Here is an example function
function scheduleAlarm() {
var h = document.getElementById('h').value;
var m = document.getElementById('m').value;
var t = document.getElementById('t').value;
alert("Successfully scheduled alram!");
setInterval(function(){
var date = new Date;
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
if (h == hours && m == minutes && t == ampm){
alert("Time to go to school, wake up!")
}
}, 5000); // will run every 5 seconds
}
Demo: CodePen

Javascript timer just for minutes and seconds

I found a JSFiddle with a timer that counts up every second.
Except i want this to work with just the minutes and seconds. No hours.
Any ideas?
DATE_OBJ.getSeconds() to get seconds of Date object.
DATE_OBJ. getMinutes() to get minutes of Date object.
setInterval to invoke handler function after every second(1000ms).
var handler = function() {
var date = new Date();
var sec = date.getSeconds();
var min = date.getMinutes();
document.getElementById("time").textContent = (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" + sec : sec);
};
setInterval(handler, 1000);
handler();
<h1 id="time" style="text-align: center"></h1>
Here's a very hackish approach - http://jsfiddle.net/gPrwW/1/
HTML -
<div id="worked">31:14</div>
JS :
$(document).ready(function (e) {
var $worked = $("#worked");
function update() {
var myTime = $worked.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() + 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$worked.html(ts[1]+":"+ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
The precise way of handling this is the following:
store the time of the start of the script
in a function that gets called repeatedly get the time elapsed
convert the elapsed time in whatever format you want and show it
Sample code:
var initialTime = Date.now();
function checkTime(){
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
document.getElementById('time').innerHTML = '' + formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return minutes + ':' + seconds;
}
window.setInterval(checkTime, 100);
You can easily change the granularity of checking the time (currently set at 0.1 seconds). This timer has the advantage that it will never be out of sync when it updates.
You can make a function that increments a counter every time it's called, shows the value as:
counter/60 minutes, counter%60 seconds
Then you can use the setInterval function to make JavaScript call your code every second. It's not extremely precise, but it's good enough for simple timers.
var initialTime = Date.now();
function checkTime(){
var timeDifference = Date.now() - initialTime;
var formatted = convertTime(timeDifference);
document.getElementById('time').innerHTML = '' + formatted;
}
function convertTime(miliseconds) {
var totalSeconds = Math.floor(miliseconds/1000);
var minutes = Math.floor(totalSeconds/60);
var seconds = totalSeconds - minutes * 60;
return minutes + ':' + seconds;
}
window.setInterval(checkTime, 100);
This might be something?
plain count up timer in javascript
It is based on the setInterval method
setInterval(setTime, 1000);

Categories