Skip to content

JavaScript time format | Short and Simple examples

  • by

To get the time or date in JS you have to use the getTime() method but returns the number of milliseconds* since the Unix Epoch. You have to use getHours(), getMinutes() and getSeconds() to get desired time format in JavaScript.

Note: JavaScript uses millisecondsas the unit of measurement, whereas Unix Time is in seconds.

Short and simple:

var now = new Date().toLocaleTimeString();
console.log(now)

Complete code

<!DOCTYPE html>
<html>
	<body>

	<script>

	t = new Date().toLocaleTimeString(); 
	alert(t)
	
	</script>

</body>
</html>

Example of JavaScript time format

It’s a very easy, Let’s see complete html code:-

<!DOCTYPE html>
<html>
	<body>

	<script>

	var d = new Date(); // for now
	h = d.getHours(); 
	m = d.getMinutes(); 
	s = d.getSeconds();
	
	alert(h+':'+m+':'+s);

	
	</script>

</body>
</html>

Output:

avaScript time format

Get and set the current time efficiently using javascript

PURE JAVASCRIPT

<!DOCTYPE html>
<html>
	<body>
	<a onclick="timeNow(test1)" href="#">SET TIME</a>
    <input id="test1" type="time" value="10:40" />

	<script>

	function timeNow(i) {
  	var d = new Date(),
    	h = (d.getHours()<10?'0':'') + d.getHours(),
    	m = (d.getMinutes()<10?'0':'') + d.getMinutes();
  	i.value = h + ':' + m;
	}
	</script>

</body>
</html>

USE: toLocaleTimeString

Present browser support to simply use: toLocaleTimeString For HTML 5 type time the format must be HH:MM.

<!DOCTYPE html>
<html>
	<body>
	<a onclick="timeNow(test1)" href="#">SET TIME</a>
    <input id="test1" type="time" value="10:40" />

	<script>

	function timeNow(i) {
  	i.value = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
	}
	
	</script>

</body>
</html>

Do comment if you have any doubts, questions and suggestions on this topic.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading