Problem with time displayed by javascript

254 views Asked by At

On some computers the time is displayed with a 1 plus (as if daylight saving time is active), and on other PCs the time is normal.

On computers that show the wrong time on the site, on the PC itself the time is right, but on the site it shows 1 hour more.

How can I fix this problem?

In Brazil daylight saving time was extinguished from this year.

HTML:

<input name="ANOATUAL" type="hidden" id="ANOATUAL" value="<?php echo date("Y"); ?>">
<input name="TIMEATUAL" type="hidden" id="TIMEATUAL" value="<?php echo strtotime(date("Y-m-d H:i:s")); ?>">
<td id="relogio"></td>

JavaScript:

function iniciaCronometro(){

    var timeAgora = parseFloat(document.getElementById("TIMEATUAL").value);
    var anoAgora = document.getElementById("ANOATUAL").value;

    var myDate = new Date(timeAgora * 1000);
    var dataAtual = myDate.toLocaleString();

    var t = dataAtual.split(anoAgora);
    var horaAtual = trim(t[1]);

    var tempo = horaAtual.split(":");

    var h = tempo[0];
    var i = tempo[1];
    var s = tempo[2];

    document.getElementById("relogio").innerHTML = h+':'+i;
    document.getElementById("TIMEATUAL").value = (timeAgora + 1);

    setTimeout("iniciaCronometro()",1000);

}

Trim function:

function trim(str){
    return str.replace(/^\s+|\s+$/g,"");
}
2

There are 2 answers

5
Frazer On BEST ANSWER

As this brilliant book suggests "Best practice: avoid the built-in Date"!

As we have discussed in chat, the following works for you.

HTML:

  <td id="relogio" data-server-time="<?php echo date('Y,m,d,H,i,s'); ?>"></p>

Javascript:

let agoraValue = 0;

const doDom = () => {
  const relogio = document.querySelector("#relogio");
  const b = relogio.getAttribute("data-server-time").split(",");
  const agora = new Date(b[0], (b[1]-1), b[2], b[3], b[4], b[5]);
  agoraValue = agora.valueOf();
  setInterval(iniciaCronometro,1000);
};

const iniciaCronometro = () => {
  const myDate = new Date(agoraValue);
  const h = myDate.getHours();
  const i = ("0" + String(myDate.getMinutes())).slice(-2);
  const timeAgora = parseFloat(document.getElementById("TIMEATUAL").value);
  relogio.innerHTML = h+':'+i;
  document.getElementById("TIMEATUAL").value = (timeAgora + 1);
  agoraValue = agoraValue + 1000;
};

// Await DOM to be loaded
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', () => {
    doDom();
  });
} else {
  doDom();
}
1
Constantin Trepadus On

Can i advice you to use a library which will solve you most problems and time consumed with parsing/formatting/etc of dates and times ?

https://momentjs.com/

If you do not want to use it, you should always use an international time/date standard then create custom functions for formatting for each country/language you want to render to.