1

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.

DGB
  • 1,252
  • 2
  • 16
  • 32

2 Answers2

1

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);

A.Khouilid
  • 51
  • 1
  • 8
1

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>
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48