Reputation: 25
Im really new to this. I want this js to update every scond so it acts like a clock or to display time
Maybe using setInterval? I dont know how to do that
Here's my code
Ignore the bahasa language on my code
date = new Date();
menit = date.getMinutes();
jam = date.getHours();
hari = date.getDay();
tanggal = date.getDate();
bulan = date.getMonth();
tahun = date.getFullYear();
document.write(tanggal+" "+arrbulan[bulan]+" "+tahun+"<br>"+jam+" : "+menit);
Upvotes: 2
Views: 2709
Reputation: 462
This should work:
<p id="date"></p>
<script>
setInterval(function(){
date = new Date();
seconds = date.getSeconds();
menit = date.getMinutes();
jam = date.getHours();
hari = date.getDay();
tanggal = date.getDate();
bulan = date.getMonth();
tahun = date.getFullYear();
document.getElementById('date').innerHTML = tanggal+" "+((bulan+1)%12)+" "+tahun+"<br>"+jam+" : "+menit+" : "+seconds;
},1000);
</script>
Upvotes: 1
Reputation: 328
Well, you could target div in your html code with:
const myDiv = document.getElementById('myId');
and then use it to set it's inner text like this:
setInterval(() => {
myDiv.innerText = myFunction();
}, 1000);
where myFunction is:
const myFunction = () => {
date = new Date();
menit = date.getMinutes();
jam = date.getHours();
hari = date.getDay();
tanggal = date.getDate();
bulan = date.getMonth();
tahun = date.getFullYear();
return tanggal + ' ' + arrbulan[bulan] + ' ' + tahun + '<br />' + jam + ' : ' + menit;
}
Upvotes: 1
Reputation: 468
Yes. setInterval
would be the way.
What you need is to wrap your code that generates the date in:
setInterval(function() {
// Load the date here every second
document.getElementById('your-date-element').innerHTML = YOUR_DATE_HERE
}, 1000)
Substitute your-date-element
for the ID of the element where you want your date to go and YOUR_DATE_HERE
for the date in the format you want.
This code will run every 1000ms (1 second) and update the date accordingly.
Upvotes: 1