How can I make a clock with Brazilian time in real time

0

I want to make a clock with Brazilian time, that whenever it passes a second it shows that it happened, that is to say.

It's 14:10:12, 14:10:13 etc ...

How can I do this?

Thank you

    
asked by anonymous 14.10.2016 / 19:34

3 answers

6

A very simple way to do this, using timezone :

    var myVar = setInterval(myTimer ,1000);
    function myTimer() {
        var d = new Date(), displayDate;
       if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) {
          displayDate = d.toLocaleTimeString('pt-BR');
       } else {
          displayDate = d.toLocaleTimeString('pt-BR', {timeZone: 'America/Belem'});
       }
          document.getElementById("demo").innerHTML = displayDate;
    }
<div id="demo"></div>
    
14.10.2016 / 19:53
1

With jQuery, I did it once:

var $clock = $('#real-clock');

setInterval(function () {

    $clock.html((new Date).toLocaleString().substr(11, 8));

}, 1000);

You can do with pure javascript too:

var clock = document.getElementById('real-clock');
    

setInterval(function () {
    clock.innerHTML = ((new Date).toLocaleString().substr(11, 8));  
}, 1000);
    
<div id="real-clock"></div>

I used the setInterval with the second parameter 1000 to make the update occur every 1 second.

    
14.10.2016 / 19:40
1

Getting the Date by Javascript will always return the current time of the computer where Javascript runs (on the client), so if the user's clock is incorrect, your clock will also be.

I believe the safest way is to take these times from the server running the application.

For the purpose of explanation I will leave everything together, but then I advise you to make a PHP file and get the information with an AJAX from time to time to stay in sync, so you can use a server NTP to keep it always synced.

(It is easier for you to ensure the time of the server than to guarantee the time on the client)

<html>
<input type="text" id="hora"/ >
<script>
(function() {
    var time=new Date(<?=gmmktime()?>000);  // 000 -> transforma os segundos retornados pelo PHP em milissegundos que são esperados pelo Javascript
    var hora = document.getElementById('hora');
    setInterval(function () {
        hora.value = ((new Date(<?=gmmktime()?>000)).toLocaleString().substr(11, 8)); 
    }, 1000);
    })();
</script>
</html>
    
14.10.2016 / 21:42