Third day of my 100 days of code.
Digital Clock:
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Digital clock</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<h1>Digital Clock</h1>
<div id="clock">10:24:35</div>
<script src="index.js"></script>
</body>
</html>
We need to add a div with a time which can be replaced by .innerHTML
JS Code:
function showTime() {
let today = new Date();
let hours = today.getHours();
let minutes = today.getMinutes();
let seconds = today.getSeconds();
let period = 'AM';
console.log(today);
console.log(hours);
}
showTime();
Create a function showTime() and new Date() will give the current date. Get hours, minutes and seconds using function and check the current time in console.The hours will be displayed in 24 hour format.
const time = `${hours} : ${minutes} : ${seconds} ${period} `;
document.getElementById('clock').innerHTML = time;
Display the time in UI by replacing the div value.Now the time is displayed in 24 hr format but each time for updating the time, need to reload the page.
setInterval(showTime,1000);
For that purpose we are using setInterval.This function evaluates the function for every 1s.
To display in 12 hr format set the condition:
// Set the clock in 12 hr format
// If hours is equal to 0 at midnight, we set to 12, and if greater than 12, we will
//subtract it from 12.
if (hours == '0')
{
hours = 12;
}
if (hours > 12) {
hours -= 12;
period = 'PM';
}
// when the hrs is less than 10, we are concantenate with 0, otherwise leave it hrs.
hours = hours <10 ? `0${hours}` : hours;
minutes = minutes <10 ? `0${minutes}` : minutes;
seconds = seconds <10 ? `0${seconds}` : seconds;
To view the full code, check Github
Top comments (0)