Display the current time HH:MM for a given timezone

snippet

Originally posted as GitHub Gist on 16 May 2018 , updated at 16 Nov 2020 (details)


Source: https://gist.github.com/paulera/9a8a8c293926b1725d746b9327152d35

Description: Display the current time HH:MM for a given timezone


timezone-clock.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<html>
<body>
	
<!-- See live at https://codepen.io/paulera/pen/BPwPNw -->

<p class="clock" timezone="+2"></p>
<p class="clock" timezone="+4"></p>
<p class="clock" timezone="-7"></p>

<script>

function dateToText(date) {
    var hours = date.getHours()
    var minutes = date.getMinutes();
    // var seconds = date.getSeconds();
    if (minutes < 10) minutes = '0'+minutes;
    //if  seconds < 10) seconds = '0'+seconds;
    if (hours < 10) hours = '0'+hours;
    return hours + ":" + minutes; // + ":" + seconds;
}


function updateClocks() {
	for (var i = 0; i < window.arrClocks.length; i++) {
		var clock = window.arrClocks[i];
		var offset = window.arrOffsets[i];
		clock.innerHTML = dateToText(new Date(new Date().getTime()+offset));
	}
}

function startClocks() {
	clockElements = document.getElementsByClassName('clock');
	window.arrClocks = []
	window.arrOffsets = [];
	var j = 0;
	for(var i = 0; i < clockElements.length; i++) {
		el = clockElements[i];
		timezone = parseInt(el.getAttribute('timezone'));
		if (!isNaN(timezone)) {
			var tzDifference = timezone * 60 + (new Date()).getTimezoneOffset();
			var offset = tzDifference * 60 * 1000;
			window.arrClocks.push(el);
			window.arrOffsets.push(offset);
		}
	}
	updateClocks();
	clockID = setInterval(updateClocks, 1000);
}

setTimeout(startClocks, 100);

</script>