I’m trying to make a simple live clock and a dd/mm/yy output on page,first function seems to work fine , but unfortunately the second function is not displaying on the page for some reason , tried everything but didn’t helped. I would be grateful if you could help me. Thank you in advance
setInterval(function clock() {
var date = new Date();
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday ", "Thursday", "Friday", "Saturday"];
var day = date.getDay();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
var Part = (hour >= 12) ? 'PM' : 'AM';
if (hour == 0 && Part == 'PM') {
if (minute == 0 && sec == 0) {
hour = 12;
Part = 'Noon'
} else {
hour = 12;
Part = 'PM'
}
}
if (hour > 12) {
hour = hour - 12;
}
var curentday = ('<br></br>' + 'Today is: ' + daylist[day]);
var time = ('Current time is : ' + hour + Part + ': ' + min + ': ' + sec + curentday);
document.getElementById('time').innerHTML = time;
}, 1000);
setInterval(function display() {
var date = new Date();
var date = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var fullDate = ('Current date is :' + date + ':' + month + ':' + year);
document.getElementById('x').innerHTML = fullDate;
}, 1000);
body {
background-color: red;
}
#time {
color: white;
font-size: 3vw;
font-family: Arial, Helvetica, sans-serif;
font-weight: 900;
text-align: center;
margin: 20%;
}
#x {
color: white;
font-size: 3vw;
font-family: Arial, Helvetica, sans-serif;
font-weight: 900;
text-align: center;
margin: 50%;
}
<div id="time"></div>
<div id="x"></div>
4
Answers
When you did
var date = date.getDate();
then you have overriden the value ofdate
with a numeric value (date of month). Removing that line fixes the issue. I have also taken out the function definitions from inside thesetInterval
call to make it more readable and to ensure that they are called in the correct order, regardless of the Javascript implementations and versions. (I do not anticipate the callback of the secondsetInterval
call to ever be called before the first, but it’s always better to know that things work correctly rather than hoping and believing. Additionally, it’s much more readable if we separate business logic from event handling)this is a modified version of the code, i changed "date" variable to "day" to be more explicit and i changed
getDate()
bygetDay()
I think this what you looking for
Beside @CBroe’s answer on the fact that you’re overriding the
date
variable, this is why it runs the first time – but 2nd time it uses the output fromdate.getDate()
I want to suggest a simpler way to describe time:
You do not need to do all those calculations. JavaScript has been improved and includes its own i18n (internationalization) library i.e.
Intl
which includes localization formatting.