Javascript clock with NTP or server time

Asked

Viewed 1,771 times

4

I have the code below, which displays a clock on a page, which serves to record factory intervals. It works perfectly, with the code below:

function moveRelogio(){

    momentoAtual = new Date();

    hora = momentoAtual.getHours();

    if (hora < 10) {
      hora = '0' + hora;
    } else {
      hora = hora + '';
    }

    minuto = momentoAtual.getMinutes();
    if (minuto < 10) {
      minuto = '0' + minuto;
    } else {
      minuto = minuto + '';
    }

    segundo = momentoAtual.getSeconds();
    if (segundo < 10) {
      segundo = '0' + segundo;
    } else {
      segundo = segundo + '';
    }

    horaImprimivel = hora + ":" + minuto + ":" + segundo

    document.cadastro.hora_inicio.value = horaImprimivel;

    setTimeout("moveRelogio()",1000);
}

Eventually the time displayed is not the same registered, because for registration is used the time of the AD. User can not change it as PI are used without keyboard and mouse.

Is there any way with Javascript to get the time of a server or the internet, from an NTP?

2 answers

4

If you are going to use an NTP for business use, you will probably have to pay for a license.

If you use a server platform that allows you to use PHP, . NET, Java, Ruby etc. you can mount a service that returns local and UTC times.

To consume, it would be something like the code below. Example in jQuery because I suppose you are not masochistic:

var dt;
$.ajax({
    url: "http://enderecoDoSeuServico/",
    success: function (horario) {
        dt = new Date(horario);
    }
});

For it to work there, just the variable horario be the amount of milliseconds since zero time on January 1, 1970 (in Greenwhich time zone), which is the "zero" value of the type Date Javascript. For this reason, the . NET code could be something like:

public long RetornaHorario()
{
    DateTime inicio = new DateTime(1970, 1, 1); // supondo fuso horário zero
    TimeSpan span = DateTime.Now - inicio;
    return span.TotalMilliseconds;
}

It shouldn’t be too different with the other languages you can use on the server.

Remember that there will be a latency between the call and the return service, so you will have to accept an accuracy of a few milliseconds to a few seconds depending on your setup.

  • 1

    Great answer Renan. But as I did not have time to change much the current structure of the code, I ended up finding another way. I will post it below, based on the question code. Anyway, +1. Thank you.

1


Using the same logic of the code that I had, I changed the code and now it takes the time of the server that is hosted the code. Worked perfectly:

<?php
//PEGA HORA ATUAL DO SERVIDOR
date_default_timezone_set('Etc/GMT');
$hoje = getdate();
?>
<script>
    var d = new Date(Date.UTC(<?php echo $hoje['year'].",".$hoje['mon'].",".$hoje['mday'].",".$hoje['hours'].",".$hoje['minutes'].",".$hoje['seconds']; ?>));
    setInterval(function() {
        d.setSeconds(d.getSeconds() + 1);
        //EXIBE O HORÁRIO COM 2 DIGITOS
        $('#hora_inicio').val((("0" + d.getHours()).slice(-2) +':' + ("0" + d.getMinutes()).slice(-2) + ':' +  ("0" + d.getSeconds()).slice(-2) ));
    }, 1000);
</script>

And in HTML:

      <tr>
          <td>Hora Atual:</td>
          <td><input type = "text" style="font-family: Verdana, Geneva, sans-serif; height: 40px; font-size: 30px;" readonly="true" id="hora_inicio" name = "hora_inicio" size = 12></td>
      </tr>

Ending:

inserir a descrição da imagem aqui

Browser other questions tagged

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