How to update time automatically using strftime

Asked

Viewed 814 times

0

I’m putting time and date to you showing on my site, I’m doing like this:

echo utf8_encode(strftime("%X - %m %B, %Y" ))  ;

But the time this static is only updating when it recharges the page, I wanted to know how to keep it updating normally, as if it were a clock I think it should be with javascript. Someone can help?

1 answer

1

Yes, this requires Javascript. HTTP requests do not store states on the server (stateless) and, therefore, the PHP script stops running after returning the reply to the request. This way, only the time (of the server) that the code was executed will be displayed.

Javascript

Removed Javascript Solution from here:

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>

It is nothing more than a function that recovers the values of hour, minute and second through the methods getHours, getMinutes and getSeconds of the object Date. After, you format minutes and seconds to display "01" instead of just "1", for example. You also use the function setTimeout Javascript to keep the time count running.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.