Display accurate local time on web site? - javascript

I've been asked to display the 'correct' time on our website which I frankly feel is rather pointless as 'correct' can be interpretted in such a variety of ways.
Our current method definately results in an inaccurate time as it uses a server control rendering JavaScript that runs onload using the datetime from the server as a parameter to create a clock object in JavaScript that finally renders on the page and then starts incrementing the clock. Between the server processing, network latency and client-side performance (there's plenty other stuff running onload) the clock ends up way off the actual server time and who knows compared to the client PC.
So to get the 'correct' time shown I could;
Use local PC time and pass new Date() to the JavaScript clock object. Pros: Should be as close to the PC clock as possible. Cons: Not sure how accurate the PC clock is let alone in which timezone.
Use web service for TCP request to NTP server to update clock on web page. Pros: If local PC also sync'd to NTP will be accurate and best possible match. Cons: Will have to handle all the timezone adjustments relative to our servers. If PC clock is out will still have mismatch.
Do I implement my own web service or use something like; Earth Tools or World Time Web Service (EDIT: link removed - now 404)
Here's a blog post from Jon Galloway on Atomic Clock Web Service which is pretty old and yet ranks high when I google and he doesn't reach a conclusion.
Hoepfully I can win the argument with management why syncing to our server clock (GMT) doesn't makes sense if your not in that timezone and why we even need to match a local PC.
Any angles on this I'm missing?

I needed to show the accurate time to clients in an auction web app. You can send the current server time with the page and have the javascript initialize right away without waiting for the rest of the page to load. So the, you only are dealing with network latency which in the worst case is not likely to be more than a couple of seconds.
After that, you're pretty darn close to accurate time. As long as your Javascript timer code is written properly, you're not going to far out of sync before the next page load. But I have seen a lot of bad JS clock code. (Hint: Date() good, setTimeout() bad.)
If you have an application that users are going to be sitting on for a long time, just refresh your time sync either by reloading the page or Ajax.
I wouldn't worry about time zones, just use UTC time so there is no confusion about what time things will happen.

First, be certain that your client is aware that Windows, Linux, and OSX all have built-in clocks that are almost always visible to the users (or made visible very easily). Also, be certain that your client is aware of physical clocks that are often located near any kiosks that might be setup to hide the built in clock from the operating system.
If you know that, and your client still wants a clock on your website, have your client define "correct" time, then implement the solution that matches their definition (both of your solutions seem like they would take care of the two most-likely definitions).

you can use geo targeting to know the physical location of a website visitor and in your database stored the (GMT - XX:XX) of the zone and then calculate the time based on the location of the request. that is going to save the long trip to any third party web service.

Another way you can implement it is using IP Geolocation. There are services that can tell you where your user is connecting from based on it's ip (usually including their timezone) and combining that information with your server's realtime clock you can show the user it's local time.
It's far from perfect, specially with corporate users that might seem to be connecting from somewhere they are not (I live in Argentina, but my work internet connection is trough my employeer that is an American company, so every website assumes I'm located in the US)

Handle time in UTC.
Have users tell you what zone they want to use.
If your users have persistent profiles, persist the choice.
Always display UTC and Local Time side by side and clearly labelled.
You can also display an arbitrary number of user specified zone clocks. Vista
does this and I remain surprised at how
handy it is.

Related

React Native Get Time In Seconds From API

I am running a chat application and want to implement correct timestamps on client side, even if the devices' times might be different.
For example, I have iOS device which has current time 14:00 and Android device 14:05 (while actual time might be 14:03). They are both set to manual device times so I would need to calculate their offset from server's time.
Date would not work in this case because it returns client time.
I couldn't find any time APIs which could help me in this case. Is there any other approach?

Time based Code execution in Javascript PHP

I have a web application in PHP and Javascript where i want to apply a time based question generation. I have preset of code that will be executed at a specific time which will generate the question.
Now i am thinking that how can i apply this. Here are some the information regarding the web
Web is running on wamp server and there are almost 100 users used it regularly (every day). They login in the website two time between 9-11am and 2-6pm.
The question geneartion time should be at 4pm.
Now, i can make use SetTimeOut and Javascript Date object in order to acheive the desire functionality: Here
function checkVotingQuestionTime()
{
var currentTime = new Date();
if(currentTime.getHours() >= 16 && currentTime.getHours() < 23)//check the time from user OS
{
checkVoteQuestionGenerated();
}
}
function checkVoteQuestionGenerated(){
//query to php check question exists
//if no
//then generate question
}
And Register it at document ready event in main page(after login). This code will be open for all users.
$jq(document).ready(function() {
setInterval(checkVotingQuestionTime, 60000);
}
As it appear that, this is not feasible code, because
It will be run from every client (set timeout and server hit
regularly and if i also get time from server than it will more often hit on server)
A user can change the system time to run above code.
Multiple question can be generated if two clients simultaneously check that the question is not generated so generate the question.
So how can I control above limitations or is there any other proper solution available?
Having 100 clients poll the server every few minutes is not a big deal. Every time they open a page on your website that's in effect polling the server. So moving the date check to php on the server side is the best solution for what you have currently set up.
If you don't like the idea of having the client poll the server every now and then for aesthetic reasons (and I can appreciate that), for example you want the question to be refreshed at 16:00 on the dot, you could look into using a sockets. This, in effect, means the client is listening to any changes sent from the server, without the need to poll it, and updates when necessary.
Socket.io is easy to use, but not the simplest when it comes to interfacing with php. I don't know if you're familiar with Node.js but here's a small discussion some others had regarding sockets and php:
What is the best way to use websockets along with PHP and MySQL scripts?

Capturing Client Machine time in web applications

We are currently developing a Web Application for one of our clients who is interested in selling it across continents. Now one of the features of the web application requires the application to capture the local time of the machine the client is using. I have looked for various options on the forum and using javascript seems to be the only option. Now the question is what happens when a user has javascript disabled on his machine.
Is there any better alternative for this since this is paramount for the application to capture the client machine time/ date.
Eagerly awaiting a response.
there is no real way to get the exact user time without javascript... I mean if the user disables javascript you could try to get the user location from IP and then set the correct time in your DB.
I would suggest you to offer a possibility to change the user time zone so the user can set up the correct time in the settings.

How does Google Analytics Real Time work?

I'm wondering how Google Analytics Real Time user interface works, what's the technique ? Do they use long-polling from the client to keep the UI statistics instantly up to date by delivering realtime information from the server to the client?
I just open Chrome dev tool on network tab and there is a infinite request on https://www.google.com/analytics/realtime/bind
Does anybody know the trick? It works flawless...
The below refers to how the real time data is collected, not how the UI updates. (It looks like the UI is just using AJAX polling on the client-side, though)
No special polling or client-side technique is used. Data collection is the same as it always has been.
Instead, Google Analytics will assume that someone who's triggered a pageview in the last 5 minutes is still an "active" visitor.
From e-nor:
These visitors have been active in the last 5 minutes, any one not active for over 5 minutes is dropped.
I was one of two people who built the first version of the Realtime Analytics UI. We used Closure's BrowserChannel.

Server polling intervals for a javascript chat client

I'm building a basic little AJAX shoutbox/chat for my website, but I'm not sure exactly how to implement the server polling.
Here's the basic program flow I'm thinking of:
User comes to page and is shown the last 10 messages
To get messages sent by others, the client javascript would request a URL with a timestamp parameter (set to the value of the last message the client received)
The server returns all messages (up to a max of 10) since that timestamp.
The only issue is how often to poll the server. Obviously it should poll each time a new message is added, but when you're just reading others' messages it needs to automatically update.
Should it be a set time limit? eg: every 10 seconds. Or, should it vary depending on usage? eg: Check after 5 seconds. If there's no messages, don't check for another 10 seconds. If there's still no new messages, check in 15 seconds, then 20, up to maybe once every 30 seconds max. Each time there's a new message detected reset your timer back down to 5 seconds and start again.
I'm just concerned about putting unnecessary stress on the server, considering that we could have hundreds of users concurrently online.
...or have I got the whole thing wrong? Is there a better way to implement a basic javascript chat?
You might want to look into what are known as Comet programming techniques to stream information down to your users, rather than having the client poll the server. This is actually a family of techniques, some of which may work better than others depending on the circumstances, such as what kind of server you're using and what kind of client compatibility you need.
If your server can handle a large number of open connections at a time (as in, it does not use an entire thread or process per connection, such as nginx or an erlang based server), you may wish to use a long polling technique, where as soon one message is received, the client immediately requests another message. If there are no messages available, the server simply keeps the connection open, possibly sending occasionally dummy data as a keepalive, until a message becomes available.
Comet, described by Brian is a nice technique, but requires session support on the server, which is probably more advanced than you care to implement for a simple chat box.
The best way to implement polling intervals is to imagine you having a chat window which you can minimize to do other stuff, or open to see if you have new messages. When you are in the middle of a conversation, you'll switch to it (poll) frequently. If you don't get any messages for a while, you will start looking rarer and rarer until you only check it occasionally.
Assuming you don't need to do real-time typing, you can probably poll every 3 seconds or so when at peak activity, and if nothing shows up for 5-10 polls, start to crank the interval up (perhaps doubling it every time) until it hits 30-60 seconds. Getting a message back should reset the poll interval back to a few seconds, while sending a message should poll instantly, but probably doesn't need to effect the frequency of polling otherwise.
Honestly, if you are implementing a “basic little AJAX shoutbox/chat”, things like Jabber, Comet etc are overkill for you. These things will require you to run additional
servers/proxies to take the load of the app server and db.
When you think about stuff like presence management (“Joe is typing...”), then things get overly complex for your app (considering “chat” is not your prime focus).
Think about adding widgets from providers like Meebo and Userplane. Once you scale think about the Jabber and the like…
You should check to see if the other user is typing every 5 seconds or so, if the other user is typing, then you can check every 1 second to see if the user has sent a new message. Really though, you should be able to check every 1 second to see if other user is typing and if they are then every .25-.5 second check to see if new message has been sent. With broadband being so generally accepted on the inet, shouldn't be a problem. Go with the longer poll timeout for a dial-up access.
This is a very hard question, keep abuse in mind. Malicious users will hit you as often as possible, with the earliest timestamp faked so as to cause stress on your DB server. Be sure to validate that timestamp, or ignore it, because shouldnt everyone be in the same time anyway?
You can send the polling interval to the user as a function of the other user's response time. That's the best kind of dynamic I think.
http://jabbify.com/home/comet_service
This is a free comet based chat service by the guys who did the jmvc framework. Haven't tried it yet, but looks promising.
The professional way of doing this is with a WebSocket javascript connection. You can use a free service like https://socketsbay.com/ for example, and connect using
// Create WebSocket connection.
const socket = new WebSocket('wss://socketsbay.com/wss/v2/[ChannelId]/[ApiKey]/');
// Connection opened
socket.addEventListener('open', function (event) {
socket.send('Hello Server!');
});
// Listen for messages
socket.addEventListener('message', function (event) {
console.log('Message from server ', event.data);
});
You can forget about server pooling time because it will be realtime.

Categories

Resources