简体   繁体   中英

How to show real-time server date and time on Nodejs

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.

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));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM