Get date and time regardless of system time

2

Well, I'm having a hard time getting the date and time in JavaScript when the computer or system is having this incorrect data.

  • Official time: 08:35 - 07/14/2016 - Brasilia timetable
  • Computer Time: 23:46 - 7/12/2016

No matter what method I try in JavaScript, the time always comes from Hora do computador , even if you try getUTCDate() , getTimezoneOffset() , etc ...

Is there any way to fix this problem with just JavaScript? Or do I really need to rely on a time taken directly from my server?

  

Note: It is important that the time is correct because it controls the e-commerce operation of the site.

    
asked by anonymous 14.07.2016 / 13:40

2 answers

8

There is no way.

The problem is not a format or a time zone, it is the hardware error that provides the time. JavaScript only takes what the browser provides. The browser only takes what the operating system provides. The OS only provides what the hardware provides. Only the user can change the time since there is no API in JavaScript to change the time of the computer.

The solution is to ask the server for the time. If you need to keep the schedule up to date, you can use a formula to get the computer time offset in relation to the correct time, then take the computer time and apply that shift before showing.

    
14.07.2016 / 13:45
2

I tried to build an example using the ideas suggested by @bigown , @LuizVieira and @GustavoTinoco

var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://www.timeapi.org/utc/now.json?callback=setDtServer";

var dtServer = null;
var dtClient = null;

//se preferir pode informar um local especifico: ["pt-BR"]
//ou uma lista de locais esperados: ["pt-BR", "pt-PT", "en-US"]
//caso informe uma lista vazia, ele vai tentar inferir o local pelo sistema.
var locales = [];
var formater = new Intl.DateTimeFormat(locales , {
  //é possivel informar o time-zone usando uma string no formato IANA
  //você pode encontrar a lista completa em:
  // http://www.iana.org/time-zones
  // https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
  //No exemplo abaixo estou usando o Timezone de Fortaleza, que difere um
  //pouco do de Brasília, por não fazer parte do Horário de Verão.
  //novamente o valor default vai refletir o que for informado pelo sistema.
  timeZone: "America/Fortaleza",

  year: "numeric",
  month: "numeric",
  day: "numeric",
  hour: "numeric",
  minute: "numeric",
  second: "numeric",
  timeZoneName: "long"
});

function getData() {
  var diff = dtServer.getTime() - dtClient.getTime();
  var data = new Date();
  data.setTime(data.getTime() + diff);
  return data;
}

function setDtServer(json) {
  dtServer = new Date(json.dateString);  
  dtClient = new Date();
  document.head.removeChild(script);  
}

document.head.appendChild(script);
window.setInterval(function () {
  var data = getData();
  console.log(formater.format(data));
}, 1234);

For more information on Internationalizing Dates with JavaScript: Intl.DateTimeFormat

If you need a Polyfill for Intl: Intl.js intl-locales-supported

    
14.07.2016 / 15:27