Display realtime date and time using JavaScript

setInterval() is a method which can be used to execute JavaScript script at specified intervals. We use it to display time from Date() class.

HTML

<div id="time"></div>

JavaScript

<script type="text/javascript">
  var time = document.getElementById("time");
  function showTime() {
    var date = new Date().toLocaleString("en-US", {timeZone: "Asia/Singapore"});    
    time.innerHTML = date;
  }
  setInterval(showTime, 1000);
</script>

With custom format

<script type="text/javascript">
	var time = document.getElementById("time");
	function showTime() {
	  var d = new Date();				  			 
	  time.innerHTML = d.getFullYear() + '-' + d.getMonth() + '-' + d.getDate() + ' ' + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	}
	setInterval(showTime, 1000);
</script>

Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close