js gets the current time and updates it in real time

You can use JavaScript's `Date()` object to get the current time, and use the `setInterval()` function to implement real-time updates.

Here is a sample code:

<p id="time"></p>
function updateTime() {
  var now = new Date();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();
  var timeString = hours.toString().padStart(2, '0') + ":" + 
                   minutes.toString().padStart(2, '0') + ":" + 
                   seconds.toString().padStart(2, '0');
  document.getElementById("time").innerHTML = timeString;
}

// 每秒钟更新一次时间
setInterval(updateTime, 1000);

This code will format the current time into the form `xx:xx:xx` and display it in the element with the id `time`. At the same time, the `updateTime` function is called every second to update the time.

Guess you like

Origin blog.csdn.net/qq_68299987/article/details/135178208