Function to pick up days of the week

Asked

Viewed 75 times

1

I am making a watch that also shows the days of the week, but I would like to be able to show the value with the full name. I even managed to do this by doing a lot of if, but I wanted to do a function instead, how do I do? I use the for?

function carregar(){
    setInterval(() => {
        let data = new Date()
        let diasemana = data.getDay()
        let dia = data.getDate()
        let mes = data.getMonth() + 1 //Coloquei +1 porque o resultado estava sendo o mês anterior
        let ano = data.getFullYear()
        let hora = data.getHours()
        let min = data.getMinutes()
        let seg = data.getSeconds()
        let hou = data.getHours()
        let pe = "AM"
        let dw = ["Domingo", "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado",]
        let mo = Array["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"]
        let dias = window.document.getElementById('dias')
        let relogio = window.document.getElementById('relogio')

        dias.innerHTML = `${diasemana} ${dia} / ${mes} / ${ano} `
        relogio.innerHTML = `${hora} : ${min} : ${seg} oi`
        
        if(diasemana == 0) {
            diasemana = dw[0]
        } else if(diasemana == 1) {
            diasema = dw[1]
        } else if(diasemana == 2) { 
            diasemana = dw[2]
        } else if(diasemana == 3) {
            diasemana = dw[3]
        } else if(diasemana == 4) {
            diasemana = dw[4]
        } else if(diasemana == 5) {
            diasemana = dw[5]
        } else {
            diasemana = dw[6] }
        
        //AM e PM
        if(hou >= 12){
             pe = "PM";
        } if(hou == 0){
            hou = 12;
        } if(hou > 12){
             hou = hou - 12;
        }
        //Mudando para String os dias da semana

        dias.innerHTML = `${diasemana} ${dia} / ${mes} / ${ano} `
        relogio.innerHTML = `${hora} : ${min} : ${seg} ${pe}`
    }, 1);
}
  • You want them to ifs turn a function or I can replace it with a for?

1 answer

6

Basically, in that if:

if(diasemana == 0) {
    diasemana = dw[0]
} else if(diasemana == 1) {
    diasemana = dw[1]
    etc...

You are doing "if the day is zero, take the zero index, if it is 1, take the index 1, etc...". If so, then directly use the value as an index:

diasemana = dw[diasemana]

Or else:

diasemana = dw[data.getDay()]

And only. The another answer (deleted) said to use for, but it doesn’t need to, because it goes through the array unnecessarily until it finds the index, but if you already know what the index is, so that the for? Not need to use for, do not force the use of something that is not necessary. If the value you already have is the same as the index, get it straight and ready.


That said, you can simplify the code, because there are ready-made formats that you can use with toLocaleDateString and toLocaleTimeString:

function carregar(){
    let data = new Date();
    let dw = ["Domingo", "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado"];
    document.getElementById('dias').innerHTML = `${dw[data.getDay()]} ${data.toLocaleDateString("pt-BR")}`;
    document.getElementById('relogio').innerHTML = `${data.toLocaleTimeString("en-US")}`;
}

document.addEventListener('DOMContentLoaded', function() { setInterval(carregar, 1000) });
<p id="dias"></p>
<p id="relogio"></p>

The locales "en-BR" and "en-US" refer respectively to Brazilian Portuguese and American English, and they already adjust the date and time formats according to what I understood you need ("en-BR" uses the date format "dd/mm/yyyy", and "en-US" uses the time format "h:m:s am/pm").

And the second parameter of setInterval is the value in milliseconds (thousandths of a second), so I put 1000 to update every 1 second (because every 1 millisecond, as you did, seems to me "exaggeration", since the clock will not show the fractions of a second).

I also put a semicolon at the end of the lines. It may sound "fresh," and I know that Javascript "accepts" the semicolon code and "works," but it avoids some bizarre situations that can occur if you don’t use them, like that one and that one (see more about this here).

I don’t even know if I really needed a job just for this, but if you really want to do this:

function getDiaDaSemana(data) {
    let dw = ["Domingo", "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado"];
    return dw[data.getDay()];
}

function carregar(){
    let data = new Date();
    document.getElementById('dias').innerHTML = `${getDiaDaSemana(data)} ${data.toLocaleDateString("pt-BR")}`;
    document.getElementById('relogio').innerHTML = `${data.toLocaleTimeString("en-US")}`;
}

document.addEventListener('DOMContentLoaded', function() { setInterval(carregar, 1000) });
<p id="dias"></p>
<p id="relogio"></p>


External lib

If you want/can use an external lib, an alternative is Moment js.. To have the name of the day of the week in Portuguese, you will need the version with locales:

moment.locale('pt-BR'); // mudar idioma para português

function carregar(){
    let data = moment();
    document.getElementById('dias').innerHTML = data.format('dddd DD/MM/YYYY');
    document.getElementById('relogio').innerHTML = data.format('h:mm:ss A');
}

document.addEventListener('DOMContentLoaded', function() { setInterval(carregar, 1000) });
<script src="https://momentjs.com/downloads/moment-with-locales.min.js"></script>

<p id="dias"></p>
<p id="relogio"></p>

Another alternative is the Luxon:

function carregar(){
    let data = luxon.DateTime.local();
    document.getElementById('dias').innerHTML = data.setLocale('pt-BR').toFormat('EEEE dd/MM/yyyy');
    document.getElementById('relogio').innerHTML = data.toFormat('h:mm:ss a');
}

document.addEventListener('DOMContentLoaded', function() { setInterval(carregar, 1000) });
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

<p id="dias"></p>
<p id="relogio"></p>

  • I hadn’t thought of this option:let dw = ["Domingo", "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado"];&#xA; return dw[data.getDay()]; like :)

  • return ["Domingo", "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado"][data.getDay()];

Browser other questions tagged

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