Reputation: 1342
I would like to display the time in my app. However I would like to update the time automatically without having the user to refresh the page.
What I would like is to display the time Example: 11:59 then 1 minute later displays 12:00 automatically without browser refresh. Just like a normal clock.
It would also be interesting to know how to show current seconds also.
Time should be the live current time in the users location.
Upvotes: 1
Views: 1456
Reputation: 10237
Here you go using the Date()
const timeEL = document.getElementById('time');
setInterval(setTime, 1000);
function setTime() {
let date = new Date();
timeEL.innerText = `${date.getHours()}:${('0' + date.getMinutes()).slice(-2)}:${('0' + date.getSeconds()).slice(-2)}`;
}
<div id="time">
</div>
Using ReactJS, you can use Refs and the DOM to call this function and set the value.
class Times extends React.Component {
constructor(props) {
super(props);
this.timeElement = React.createRef();
}
componentDidMount = () => {
setInterval(this.setTime, 1000);
}
setTime = () => {
let date = new Date();
this.timeElement.current.innerText = `${date.getHours()}:${('0' + date.getMinutes()).slice(-2)}:${('0' + date.getSeconds()).slice(-2)}`;
}
render = () => {
return (
<div ref={this.timeElement}></div>
)
}
}
ReactDOM.render( <Times/> , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="app">
</div>
Upvotes: 1
Reputation: 71
function theTime() {
let Datte = new Date();
let H = Datte.getHours();
let m = Datte.getMinutes();``
let s = Datte.getSeconds();
if (H < 10 ){
H = "0" + H;
}
if (m < 10 ){
m = "0" + m;
}
if (s < 10 ){
s = "0" + s;
}
document.getElementById("time").textContent = `${H} : ${m} : ${s}`
}
setInterval(theTime);
<div id="time"></div>
setInterval(theTime);
Upvotes: 1