I am designing a basic digital clock.
But the code doesn’t seem to work.
I am attaching my code:
My clock.js file:
setInterval( function() {
var currentTime= new Date().toLocaleTimeString(); // gets time from local computer
var hours= currentTime.getHours();
var minutes= currentTime.getMinutes();
var seconds= currentTime.getSeconds();
var period= "AM";
if(hours >=12){
period="PM";
}
if(hours >= 13){
hours= hours-12;
}
if(minutes <=9){
minutes = "0" + minutes; // so, 9:6 --> 9:06
}
if(seconods <=9){
seconds= "0" + seconds;
}
var clockTime= hours + ":" + minutes + ":" + seconds + " " + period;
var clockElement = document.getElementById("clock");
clockElement.innerHTML = clockTime;
}, 1000); // every 1000 milli seconds, the function will run
Here is my clock.html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="description" content="Digital Clock using JavaScript" >
<meta name="viewport" content="width=device-width, initial-scale=1.0" >
<title>Digital Clock</title>
<link rel="stylesheet" href="clock.css" />
</head>
<body>
<div id="banner"><span>Your local time</span></div>
<div id="clock">
</div>
<script type="text/javascript" src="clock.js"></script>
</body>
</html>
The setInterval() function doesn’t seem to work.
Or, is there any error elsewhere?
2
Answers
In this line:
You’re setting
currentTime
to a string, not a Date object, so when you’re asking forcurrentTime.getHours()
the method doesn’t exists.Change the line to
Also, correct the typo in this line
Demo:
I would suggest you to dont set the date as "toLocaleTimeString()"
Just do this instead:
So you only need to return the new object Date(), you can use method "toLocaleTimeString" when you show/print the time.