How to create a clock
- Web Coding

 - Sep 18, 2020
 - 1 min read
 
Learn how to create a clock with HTML, CSS and JavaScript
HTML
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <link rel="stylesheet" href="style.css">
</head>
<body>
 <p id="timeDisplay"></p>
 <script src="script.js"></script>
</body>
</html>CSS
*{
 margin: 0;
 padding: 0;
}
body{
 display: flex;
 align-items: center;
 justify-content: center;
 min-height: 100vh;
 font-size: 32px;
}JavaScript
let timeDisplay = document.getElementById('timeDisplay');
function updateTime(){
 let t = new Date();
 let hours = t.getHours();
 let minutes = t.getMinutes();
 let seconds = t.getSeconds();
 let amOrPm = setToAmOrPm(hours);
 hours = convertTo12HourClock(hours);
 hours = formatTime(hours);
 minutes = formatTime(minutes);
 seconds = formatTime(seconds);
 timeDisplay.innerHTML = `${hours} : ${minutes} : ${seconds} ${amOrPm}`;
}
function setToAmOrPm(hours){
 if(hours < 12){
 amOrPm = 'am';
    } else {
 amOrPm = 'pm';
    }
 return amOrPm;
}
function convertTo12HourClock(hour){
 if(hour > 12){
 hour = hour -12;
    } else if (hour === 0){
 hour = 12
    } else {
    }
 return hour;
}
function formatTime(input){
 if(input < 10){
 input = '0' + input;
    }
 return input
}
setInterval(updateTime, 1000);If you found this blog post helpful don’t forget to check out my other projects and if you want more content follow me on
YouTube: https://www.youtube.com/channel/UC2nxqB2usQIS2c8zwVZKWEQ
Instagram: https://www.instagram.com/coding_for_the_web/
Twitter: https://twitter.com/LearnWebCoding



Comments