2

In Nodejs, how to read the date and time from the server and display in real time on my webpage? By using Javascript inside my webpage, it will pick up the date and time of the computer I'm using, not the server. I want the date and time from server.

wBB
  • 821
  • 1
  • 18
  • 39
  • Possible duplicate of [The best way to synchronize client-side javascript clock with server date](https://stackoverflow.com/questions/1638337/the-best-way-to-synchronize-client-side-javascript-clock-with-server-date) – t.niese Jul 29 '17 at 15:46
  • Hi! thanks for your attention. The way of @kkpoon has solved my problem. – wBB Jul 29 '17 at 17:24

1 Answers1

9

You may simply use socket.io to do it.

On server side, create a websocket server, publish the date time every interval (depend on your requirement, seconds, minutes, ...)

io.on('connection', function (socket) {
  socket.emit('datetime', { datetime: new Date().getTime() });
});

On browser side, subscribe the websocket and received the date time from server.

var socket = io.connect('http://your-socket-io-server');
socket.on('datetime', function (data) {
  $("#clock").text(new Date(data));
});
kkpoon
  • 1,939
  • 13
  • 23
  • 2
    It works perfectly. I'd just add in your answer, a practical example of where to find the "socket.io" in the system, instead of `http: // your-socket-io-server`. For me it's OK, but I'm saying this because it might be useful for other people. Thank you !! – wBB Jul 29 '17 at 17:39
  • I find it a little unclear where to be adding these code snippets – HCKRMVT Mar 02 '22 at 10:34
  • I followed this tutorial that aim to do the same thing: https://dev.to/suhakim/create-a-real-time-digital-clock-with-node-and-socketio-53dm – HCKRMVT Mar 02 '22 at 10:46