Get time and date independent of system time

Asked

Viewed 7,601 times

3

Well, I’m having trouble getting the date and time in Javascript when the computer, or the system has this incorrect data.

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

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

Is there any way to fix this problem only with Javascript? Or do I really need to base myself on a schedule obtained directly from my server?

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

  • Have you ever used date.toISOString();?

  • @Sergio yes, based on Hora do computador of the question, that is the result obtained: 2016-07-13T02:51:41.447Z It does everything based on system date/time

3 answers

11


There’s no way to do that.

The problem is not of format or time zone, it is error of the hardware use 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 time for the server, at least the first time to know the correct time you have control. If you need to keep the time updated you can use a formula to pick up the shift of the computer’s time relative to the right time, then take the computer’s time and applying this shift before showing.

  • 1

    It would not be possible perhaps, and alternatively, to take the official schedule of some publicly accessible webservice?

  • 3

    @Luizvieira Yes, but it falls into the matter of taking the server time, not necessarily yours. It is easier and more guaranteed (it does not depend on a newer technology that may not be available) take from your.

  • 1

    Could this be? http://answall.com/a/9244/15726

  • 1

    @Gustavotinoco not because this is PHP :P But it’s basically ported to JS with Websockets.

  • This is for JS in the question itself the guy found the answers. http://stackoverflow.com/questions/10900907/good-precision-for-sync-time-with-ntp-over-javascript

  • 1

    Or you take here http://www.timeapi.org/ then you convert the UTC time to the Brasilia time zone.. etc...

  • 1

    This last one I don’t know, but in the OS question has some interesting solutions, although I don’t know how reliable they are.

  • @Gustavotinoco Of qq way the JS is picking up from an external source, and there are already any data (the fact of being time is a detail). It is a solution to have the information, but it is not a feature that the JS has (falls in what Bigown said, the JS does not do it, would have to take from a server, and I agree that if it is to get, better of your same). Even this API needs to use JSONP, precisely to bypass CORS, which does not allow a normal Ajax to take data from another domain..

  • Although the solutions are good, if there is no way to do this JS itself, it is more viable, safe and guaranteed to make (more) a simple $http and get the current time by my own server, which by default already uses the Brasilia zone.

  • @Celsomtrindade agree.

Show 5 more comments

2

I tried to set an example using the ideas suggested by @Maniero, @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 about Date Internationalization with Javascript: Intl.DateTimeFormat

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

  • In this case, how to determine which Timezone? Because I noticed that when searching to run the script it displays 2 times: 14/07/2016 10:37:24 BRT and 09:49:22.447 there is still a small difference between times, including minutes. Note: Now I have my computer clock at the official time of Brasilia

  • @Celsomtrindade, I made an edition in the example and added some comments, maybe it will help to remedy your doubt.

  • for minutes difference, here is not happening, try to compare with some online service, such as: http://time.is

-4

const options = {
    timeZone: 'America/Sao_Paulo',
    hour: 'numeric',
    minute: 'numeric'
};
const date = new Intl.DateTimeFormat([], options);
console.log(date.format(new Date()));

Browser other questions tagged

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