I am trying to sync my laptop's time with a server's time in milli seconds. I'm using this snippet:
let diffTime = 0;
syncTimeFromServer=function(){
n=new XMLHttpRequest;
n.onreadystatechange=function(){
if(n.readyState===XMLHttpRequest.DONE&&n.status===200){
let d11 = new Date().getTime();
let lastServerDate = Number(tttt.msFormat.split('/Date(')[1].split(')/')[0]);
diffTime = new Date().getTime - lastServerDate;
}
};
dBefore = new Date().getTime();
var ttt=resetTimeZoneToTehran(new Date);
n.open("GET","/Home/GetDateTime?t="+ttt,!0);
n.send()
};
myBtn.addEventlistener('click',()=>{
diffTime += waitingForServerRespons;
console.log('diff time between my Local to Server:',diffTime);
})
I get the diff from XHR request then in Network tab of chrome I got the waiting Time For Server respond As you can see in image:
How to get waitingForServerRespons
The question is why difference between serverTime and myTime isn't stable in all cases? In some cases difference is 120 ms and others about 140 ms. So there is about 20 ms difference in all cases to each other. but I want to get exact different time of server and my laptop's in all cases to set that difference to my new Date() instances. Where have I do it wrong? Any suggestion would be great.
something is wrong. My calculations or that link which is providing the server time. Which its results is like this:
{"hour":3,"minute":13,"second":29,"msFormat":"/Date(1674863009736)/"}
Related
I'm using a script that grab a json informations from a Web App using their API and my ajax code, but if something in the Web app change, I still grab the old informations, because we have difference in Time Zone. So if I add 11 hours in My computer I get the new Informations.
So it's possible to change local time to another timezone using javascript ? Thanks.
UPDATE
I'm using ajax with Javascript, not jQuery
function getInfos(url) {
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.send(null);
oReq.responseType = "text";
oReq.onreadystatechange = function()
{
if (oReq.readyState == 4)
{
var resp = JSON.parse(oReq.responseText)
// Do Something with Data
}
}
}
You could try using timesonze-js. According to their documentation you should initialize it like this:
timezoneJS.timezone.zoneFileBasePath = '/path/to/your/tz/folder';
timezoneJS.timezone.init();
Then you can use it like so:
var date = new timezoneJS.Date('04/30/2014', 'America/Chicago');
Not exists a function to change timezone
javascript automatically takes the time zone of your computer
one way would
Use UTC() method
after
add or subtract the minutes of difference
with this you will have the time in any time zone
use gettimezoneoffset to get the minutes of difference
<div id="clock"></div>
<script>
var now = new Date(<?php echo time() * 1000 ?>);
function startInterval(){
setInterval('updateTime();', 1000);
}
startInterval();//start it right away
function updateTime(){
var nowMS = now.getTime();
nowMS += 1000;
now.setTime(nowMS);
var clock = document.getElementById('clock');
if(clock){
clock.innerHTML = now.toTimeString();//adjust to suit
}
}
This is my html code. I am a Java noob and basically found this here: PHP with javascript code, live clock. I want to adjust the format from "HH:mm:ss GMT+0100 (Romansk (normaltid))" to only "HH:mm:ss".
Try Moment.js:
clock.innerHTML = moment(now).format('HH:mm:ss');
Working Example.
BTW, you are using PHP time() to return server side time right? Just a hint, setInterval is not that accurate (see: How Accurate is Window.setInterval()) and so you will slowly introduce imprecision. If client side clock can't be trusted I would either expose the server time as Web Service or consume the time from one of the many web services already available (Time API, json-time, etc). While there will be a delay, at least it will not introduce cumulative imprecision.
now.toLocaleTimeString(false, {'hour12': false});
or instead of false - your prefered locale
This sounds a bit orthodox, i'll admit.
However i was wondering if there was a way to load a specific website using Javascript/Jquery/Ajax or HTML5?
Reason i ask is because i'm aware there's a method for using cronjobs, but i'm curious to know if there's another method that does not require cron jobs in order for it to function.
By load a specific page i'm referring to anything really, perhaps a set
of words or an iframe.
Derek
You would have to have a page already loaded, so let's say this is the javascript in index.html:
var now = new Date(),
then = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
0,0,0),
diff = now.getTime() - then.getTime();
that will see the milliseconds since midnight. Now the code below will redirect to a page (or text) if it's within 1 minute of midnight:
document.onload = function()
{
var now = new Date(),
then = new Date(
now.getFullYear(),
now.getMonth(),
now.getDate(),
0,0,0),
diff = now.getTime() - then.getTime();
if(diff <= 60000)
{
//Un-comment first line to go to page, second to change text of page
//window.location.href = 'pageToLoad.html';
//document.body.innerHTML = 'yourText';
}
}
Like you already know there are cron jobs (server side) wich allow you to execute some php scripts at a precise time on your server/host.
If you want that your users see different pages at a certain hour of the day(or a specific time) by loading different content with ajax . Here is a very short example.
1.ajax function for modern browsers(chrome,safari,ie10,ios,android..)
2.time check
3.get night or day content.
function ajax(a,b,c){//url,function,just a placeholder
c=new XMLHttpRequest;
c.open('GET',a);
c.onload=b;
c.send()
}
var h=new Date().getHours();
// if it's after 12pm & before 6am it returns night else day.
nightday=(h>0&&h<6?'night':'day')+'.php';
//get the data from file 'day.php' or 'night.php'
ajax(nightday,function(){
//this.response is the content
console.log(this.response);
});
if you want to execute this just once:
window.onload=function(){
var c=new XMLHttpRequest,h=new Date().getHours();
c.open('GET',(h>0&&h<6?'night':'day')+'.php');
c.onload=function(){console.log(this.response)};
c.send()
}
And from here there are now various ways to check what time it is.
on every click,on some specific clicks,setTimeout(bad),setIntervall(bad)..and much more.
night.php
<?php
//load the content for night
?>
day.php
<?php
//load the content for day
?>
Is there a way I can get the load time of a URL or page from Jquery? For example, I make ajax request to "http://www.yahoo.com", I want to know how long it took to load the page completely. I am aware of the same domain policy. But I just want to write a simple javascript utility that can let me know page load time.
I know there are tools like YSlow etc, but I want this utility to be running continuously in browser tab and alert(javascript) alert when the page load time is beyond some threshold.
Thanks,
J
Something like this should work nicely.
var startTime;
$.ajax({
// url, type, dataType, etc
beforeSend: function(xhr){
startTime = +new Date();
}
complete: function(xhr, state){
var latency = (+new Date()) - startTime;
window.console.log(latency);
}
});
I you are using $.ajax you can set a variable with the start time in a function called by the "beforeSend" option like:
var start = (new Date()).getTime();
Then set another variable with the "complete" option like:
var finish= (new Date()).getTime();
Then compare the two to get the number of seconds like:
var secs = (finish-start)/1000;
Or once you set the start variable, use "setInterval()" to check the start variable against the current time until it exceeds a threshold.
But you know there is the "timeout" option in $.ajax too, which is covered pretty well here and may be helpful:
Determine if $.ajax error is a timeout
My question is Client time only displayed, But want to display server time every seconds.
function GetCount(ddate,iid){
var date = new Date();
dateNow = date;
// if time is already past
if(amount < 0){
}
// else date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
document.getElementById(iid).innerHTML=days;
document.getElementById('countbox1').innerHTML=hours;
document.getElementById('countbox2').innerHTML=mins;
document.getElementById('countbox3').innerHTML=secs;
setTimeout(function(){GetCount(ddate,iid)}, 1000);
}
}
If you want to avoid all that network traffic checking the time with the server every second just: (1) have the server pass the time in a way that you store in a JS variable on page load; (2) also store the client time as at page load; (3) use setInterval to update the time (every 1000 milliseconds or as often as you want) by getting current client time minus client time at page load as an offset of server time at page load. (Obviously this will all go wrong if the user updates their PC clock while your page is running, but how many users would do that? And would it be the end of the world if they did?)
If you really want the actual server time every second - why? Seems a bit of a waste of bandwidth for little if any benefit, but if you must do it use Ajax as already suggested. If you're not familiar with Ajax I'd suggest using Google to find some tutorials - if you use JQuery you can do it with only a couple of lines of code. Easy.
Or put your onscreen clock in an IFRAME that repeatedly reloads itself. Just because I sometimes miss the days of IFRAMEs.
If you run into the issue that the server time is different from the client-side clock, I lookup a server time delta in minutes just once, and then I add it to the minutes of a new Date():
var refDateTime = new Date();
refDateTime.setMinutes(refDateTime.getMinutes() + getServerTimeDelta());
// ...
var serverTimeDelta;
function getServerTimeDelta(recalc) {
var xmlHttp;
if (recalc || !serverTimeDelta) {
try {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
} catch(err1) {
//IE
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch(err2) { /* swallow it */ }
}
if (xmlHttp) {
xmlHttp.open('HEAD', window.location.href.toString(), false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send('');
var serverDateTime = xmlHttp.getResponseHeader("Date");
if (serverDateTime) {
var dateNow = new Date();
var serverDate = new Date(serverDateTime);
var delta = serverDate.getTime() - dateNow.getTime();
// Convert to minutes
serverTimeDelta = parseInt((delta / 60000) + '');
if (!serverTimeDelta) serverTimeDelta = 0.01;
} else {
serverTimeDelta = 0.011; // avoid auto recalc
}
} else {
serverTimeDelta = 0.012;
}
}
return serverTimeDelta;
}
You need your server to supply the time to JavaScript, either on page load or via XMLHttpRequest.
To get the server time from the client side in javascript you will need to make an ajax call.
Do you know how to make that type of call?
You will basically make another page (or web method etc) which displays/returns the time. You will then use a XMLHttpRequest object to make the call and get the result.