top of page
Writer's pictureWeb Coding

How to create a clock

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

*{
 margin0;
 padding0;
}

body{
 displayflex;
 align-itemscenter;
 justify-contentcenter;
 min-height100vh;
 font-size32px;
}


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(updateTime1000);

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


8 views

Comments


bottom of page