0
I am creating a clock from an informed value, the problem is that the clock is not being updated.
The other problem is that the exhibition is reversed, the month is coming before the day.
What am I doing wrong? This value "Today" is displayed correctly and comes from the server, I can not take the value of the client because of the risk of changing the date of the computer.
function relogio() {
var valor = document.getElementById('Hoje').value;
var data = new Date(valor);
var dia = data.getDate();
var mes = data.getMonth() + 1;
var ano = data.getFullYear();
var horas = data.getHours();
var minutos = data.getMinutes();
var segundos = data.getSeconds();
if (dia < 10) {
dia = "0" + dia;
}
if (mes < 10) {
mes = "0" + mes;
}
if (horas < 10) {
horas = "0" + horas;
}
if (minutos < 10) {
minutos = "0" + minutos;
}
if (segundos < 10) {
segundos = "0" + segundos;
}
var dataAtualizada = dia + '/' + mes + '/' + ano + ' ' + horas + ':' + minutos + ':' + segundos;
document.getElementById('relogio').innerHTML = dataAtualizada;
}
window.setInterval(relogio(), 1000);
try to do so:
window.setInterval(relogio, 1000);
– Máttheus Spoo
@Máttheusspoo this way, if it does not pass the value of the right. But if it passes not the.
– mba
... I don’t understand. When you use setInterval, you must pass the name of the function, or declare it within setInterval. If you use the
()
within the function, it will not perform the function every 1 second, it will perform at the time it reads the line and then it will error every 1 second.– Máttheus Spoo
@Máttheusspoo I understand, but the problem is here.
var data = new Date(valor);
, when I do not pass this value, the way you spoke without () updates, when I pass the value it does not update, only displays and shows no error.– mba
Just for understanding, what is the value that is in the variable
valor
? I know you’re taking from the element, but what’s in the "today" element? today’s date? if that’s the case, you can just donew Date()
that it takes the current browser day/time.– Máttheus Spoo
It does not update because you pass a fixed date to the date object, and does not "increase" it. Then the date/time you spent will be updated every time without increasing. If you pass no value on the object, the
new Date()
will come with the time of the browser and whenever update it will take the time of the browser on which the function ran, instead of a fixed value that does not change.– Máttheus Spoo
@Máttheusspoo, The variable is taking the current server date in the following
formato 07/12/2018 10:37:06
, I can’t catch hownew Date
in this case I get from the user’s machine and he can change the time and not hit with server .– mba
Let’s go continue this discussion in chat.
– Máttheus Spoo