I have the following code that displays the user's local time:
HTML
<h1 id="time"></h1>
Script
var d = new Date();
var hours = d.getHours();
var minutes = d.getMinutes();
var mins=new Array(9);
mins[0]="00";
mins[1]="01";
...
mins[59]="59";
var MinName = mins[d.getMinutes()];
document.getElementById('time').innerHTML = hours+":"+MinName;
How can I modify this to update automatically as time passes, without reloading the page?
Here you have a real simple solution:
setInterval(function() {
var date = new Date();
$('#time').html(
date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()
);
}, 500);
You need to use setInterval http://www.w3schools.com/jsref/met_win_setinterval.asp
setInterval(function () {
var d = new Date();
var hours = d.getHours();
var minutes = d.getMinutes();
var mins=new Array(9);
mins[0]="00";
mins[1]="01";
...
mins[59]="59";
var MinName = mins[d.getMinutes()];
document.getElementById('time').innerHTML = hours+":"+MinName;
}, 1000);
Related
I have the below code loaded in the head of a small HTML file. It is meant to grab the current time, convert it to 12H, add am or pm and then set this as the document title. This appears to work as I want, until the final line where I want it to run the function every 5 seconds so the document title updates dynamically. For whatever reason this isn't working and I can't figure out why. Can anyone assist?
function tConv24(time24) {
var ts = time24;
var H = +ts.substr(0, 2);
var h = (H % 12) || 12;
h = (h < 10)?("0"+h):h;
var ampm = H < 12 ? " am" : " pm";
ts = h + ts.substr(2, 3) + ampm;
return ts;
}
var today = new Date();
var currentTime = today.getHours() + ":" + today.getMinutes();
document.title = tConv24(currentTime);
setInterval(tConv24(currentTime), 5000);
Your logic seems fine, except that currentTime is only initialized once. So, the function tConv24 is being called each time with the same value. To correct, you need to make sure you always grab the latest date time by using the Date constructor:
function tConv24(time24) {
// function implementation
}
setInterval(function() {
var today = new Date();
var currentTime = today.getHours() + ":" + today.getMinutes();
document.title = tConv24(currentTime);
}, 5000);
Check this out:
let doc, bod, I, displayTime; // for use on other loads
addEventListener('load', ()=>{
doc = document; bod = doc.body;
I = id=>doc.getElementById(id);
displayTime = ()=>{
let dt = new Date, hr = dt.getHours(), mn = dt.getMinutes(), pm = 'am';
if(hr > 12){
hr -= 12; pm = 'pm';
}
if(mn.toString().length < 2)mn = '0'+mn;
return hr+':'+mn+pm;
}
const test = I('test');
test.textContent = displayTime();
setInterval(()=>{
test.textContent = displayTime();
}, 1000);
});
<div id='test'></div>
I'm creating simple web app that shows you what date and time is it now. It works good but i want to make it to be more dynamic so you can see time counting. What is best way to do this?
var hdate = document.getElementById('time');
var body = document.querySelector('body');
var bgM = document.getElementsByClassName('bgMorning')
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
hdate.textContent = dateTime;
you could write your code inside an interval like this to update it every second.
setInterval(function(){
//write you code here to be executed every second
}, 1000);
you'll need to re-render your display element too. Use something like this
<html>
<p id="displayElement"></p>
<script>
//use this code inside your setInterval function so it re-renders every second
document.getElementById("displayElement").innerHTML = `<p>${time}</p>`;
</script>
</html>
let me know how that works!
You just need to call setInterval(func, interval_milliseconds).
Also try using template literals (e.g. ${hours}:${minutes}) to construct your strings in a more readable style.
Use let as opposed to var unless you need to support old versions of I.E.
let timeEl = document.getElementById('time');
let updateTimeEl = () => {
let today = new Date();
let date = `${today.getFullYear()}-${today.getMonth() + 1}-${today.getDate()}`;
let time = `${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}`;
timeEl.textContent = `${date} ${time}`;
};
setInterval(updateTimeEl, 1000);
<div id="time"></div>
Try this.
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
hdate.textContent = h + ":" + m + ":" + s;
// document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function() {
startTime()
}, 500);
}
startTime(); //it starts the timer
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
Not sure if your code is the best, but you can just wrap it in a setInterval.
setInterval(function(){
var hdate = document.getElementById('time');
var body = document.querySelector('body');
var bgM = document.getElementsByClassName('bgMorning')
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" +
today.getSeconds();
var dateTime = date+' '+time;
console.log(dateTime)
}, 1000)
The second argument in the setIterval function is the interval that the code runs in miliseconds. So this will print to the console every second (1000ms -> 1s)
While learning JavaScript, I found the following code:
function printTime() {
var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
document.body.innerHTML = hours+":"+mins+":"+secs;
}
setInterval(printTime, 1000);
In Codepen this does not show anything while the HTML and CSS sections are empty. The main question is: how can I insert the generated time on a specific place in the HTML document?
For example, the time should be placed in this div:
<div id="time" class="main__section--time">
/* show time here */
</div>
How can I link this function to an ID or class to show the output in this div?
You have to modify your printTime function like this:
function printTime() {
var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
// select the div by its id
document.getElementById("time").innerHTML = hours+":"+mins+":"+secs;
}
Try it in the snippet below:
function printTime() {
var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
document.getElementById("time").innerHTML = hours+":"+mins+":"+secs;
}
setInterval(printTime, 1000);
<div id="time" class="main__section--time">
</div>
Instead of document.body.innerHTML you would just use document.getElementById("time").innerHTML
You can use the document.querySelector API together with a CSS selector to reference a specific element on the page.
var timeDisplayElement = document.querySelector('#my-time');
function printTime() {
var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
timeDisplayElement.innerHTML = hours+":"+mins+":"+secs;
}
setInterval(printTime, 1000);
<div id="my-time"></div>
Use document.getElementById("time").innerHTML = ...
You need to specify the div's id with
document.getElementById ("time")
And then access to it's innerHTML property
function printTime() {
var d = new Date();
var hours = d.getHours();
var mins = d.getMinutes();
var secs = d.getSeconds();
document.body.innerHTML= hours+":"+mins+":"+secs;
}
setInterval(printTime, 1000);
So I'm making a clock and I'm trying to make it go into AM/PM mode, as of right now it's in military time. I want to make the hours go from 01-12 and minutes go from 00-59 and seconds go from 00-59. Any ideas how to edit this?
$(document).ready(function() {
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
$('#time').text(h + ":" + m + ":" + s);
setTimeout(function(){startTime()},500);}
startTime();
});
Thanks
If hours is greater than 12, subtract 12.
$(document).ready(function() {
function startTime() {
var today = new Date();
var h = today.getHours();
if (h >12) { h -=12;} // this
var m = today.getMinutes();
var s = today.getSeconds();
$('#time').text(h + ":" + m + ":" + s);
setTimeout(function(){startTime()},500);}
startTime();
});
How do I show the current time in the format HH:MM:SS?
You can use native function Date.toLocaleTimeString():
var d = new Date();
var n = d.toLocaleTimeString();
This will display e.g.:
"11:33:01"
MDN: Date toLocaleTimeString
var d = new Date();
var n = d.toLocaleTimeString();
alert("The time is: \n"+n);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function() {
startTime()
}, 500);
}
startTime();
<div id="time"></div>
DEMO using javaScript only
Update
Updated Demo
(function () {
function checkTime(i) {
return (i < 10) ? "0" + i : i;
}
function startTime() {
var today = new Date(),
h = checkTime(today.getHours()),
m = checkTime(today.getMinutes()),
s = checkTime(today.getSeconds());
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
})();
You can do this in Javascript.
var time = new Date();
console.log(time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds());
At present it returns 15:5:18. Note that if any of the values are less than 10, they will display using only one digit, not two.
Check this in JSFiddle
Updates:
For prefixed 0's try
var time = new Date();
console.log(
("0" + time.getHours()).slice(-2) + ":" +
("0" + time.getMinutes()).slice(-2) + ":" +
("0" + time.getSeconds()).slice(-2));
You can use moment.js to do this.
var now = new moment();
console.log(now.format("HH:mm:ss"));
Outputs:
16:30:03
new Date().toTimeString().slice(0,8)
Note that toLocaleTimeString() might return something like 9:00:00 AM.
Use this way:
var d = new Date();
localtime = d.toLocaleTimeString('en-US', { hour12: false });
Result: 18:56:31
function realtime() {
let time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('h:mm:ss a');
document.getElementById('time').innerHTML = time;
}, 1000)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
A very simple way using moment.js and setInterval.
setInterval(() => {
moment().format('h:mm:ss a');
}, 1000)
Sample output
Using setInterval() set to 1000ms or 1 second, the output will refresh every 1 second.
3:25:50 pm
This is how I use this method on one of my side projects.
setInterval(() => {
this.time = this.shared.time;
}, 1000)
Maybe you're wondering if using setInterval() would cause some performance issues.
Is setInterval CPU intensive?
I don't think setInterval is inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful. ... - lonesomeday
No, setInterval is not CPU intensive in and of itself. If you have a lot of intervals running on very short cycles (or a very complex operation running on a moderately long interval), then that can easily become CPU intensive, depending upon exactly what your intervals are doing and how frequently they are doing it. ... - aroth
But in general, using setInterval really like a lot on your site may slow down things. 20 simultaneously running intervals with more or less heavy work will affect the show. And then again.. you really can mess up any part I guess that is not a problem of setInterval. ... - jAndy
new Date().toLocaleTimeString('it-IT')
The it-IT locale happens to pad the hour if needed and omits PM or AM 01:33:01
Compact clock function:
setInterval(function() {
let d = new Date()
console.log(`${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}`)
}, 1000);
This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.
var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55
This is an example of how to set time in a div(only_time) using javascript.
function date_time() {
var date = new Date();
var am_pm = "AM";
var hour = date.getHours();
if(hour>=12){
am_pm = "PM";
}
if (hour == 0) {
hour = 12;
}
if(hour>12){
hour = hour - 12;
}
if(hour<10){
hour = "0"+hour;
}
var minute = date.getMinutes();
if (minute<10){
minute = "0"+minute;
}
var sec = date.getSeconds();
if(sec<10){
sec = "0"+sec;
}
document.getElementById("time").innerHTML = hour+":"+minute+":"+sec+" "+am_pm;
}
setInterval(date_time,500);
<per>
<div class="date" id="time"></div>
</per>
new Date().toLocaleTimeString()
function realtime() {
let time = moment().format('hh:mm:ss.SS a').replace("m", "");
document.getElementById('time').innerHTML = time;
setInterval(() => {
time = moment().format('hh:mm:ss.SS A');
document.getElementById('time').innerHTML = time;
}, 0)
}
realtime();
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
<div id="time"></div>
Use
Date.toLocaleTimeString()
// Depending on timezone, your results will vary
const event = new Date('August 19, 1975 23:15:30 GMT+00:00');
console.log(event.toLocaleTimeString('en-US'));
// expected output: 1:15:30 AM
console.log(event.toLocaleTimeString('it-IT'));
// expected output: 01:15:30
console.log(event.toLocaleTimeString('ar-EG'));
// expected output: ١٢:١٥:٣٠
Source