How to get the name of a day of the week having the year/month/day in number

Asked

Viewed 128 times

-1

I have a calendar that returns me by clicking on a date the month, year, and day.

I wonder if anyone has done an algorithm so that through these data, ex: 20/10/2018, I get the name of the day of the week. Ex: "Saturday"

Any idea how to do this? Any help is welcome.

I tried to:

getNomeDiaSemana() {
    //Algoritmo para descobrir o dia da semana que o usuário selecionou
    let a = ((12 - this.mes) / 10);
    let b = this.ano - a;
    let c = this.mes + (12 * a);
    let d = b / 100;
    let e = d / 4;
    let f = 2 - d + e;
    let g =  (365.25 * b);
    let h = (30.6001 * (c + 1));
    let i = ((f + g) + (h + this.dia) + 5);
    let j = (i % 7); //Resto de I por 7, onde 0=SAB, 1=DOM, 2=SEG, 3=TER, 4=QUA, 5=QUI, 6=SEX
    //Testa o resultado e retorna
    switch (j) {
        case 0:
            return "Sábado";
        case 1:
            return "Domingo";
        case 2:
            return "Segunda";
        case 3:
            return "Terça";
        case 4:
            return "Quarta";
        case 5:
            return "Quinta";
        case 6:
            return "Sexta";
        default:
            return "Erro ao tentar retornar o dia da semana";
    }
}

but falls into error.

1 answer

0

Why this whole maneuver of your code?

Turn the date into valid javascript date mm/dd/yyyy

var data = "20/10/2018";
var dataArray = data.split("/");
var d = dataArray[1] + '/' + dataArray[0] + '/' + dataArray[2];

d = new Date(d);

var nomeDias=['Segunda','Terça','Quarta','Quinta','Sexta','Sabado','Domingo']

console.log(nomeDias[d.getDay()-1]);

var data = "18/10/2018";
var dataArray = data.split("/");
var d = dataArray[1] + '/' + dataArray[0] + '/' + dataArray[2];

d = new Date(d);

var nomeDias=['Segunda','Terça','Quarta','Quinta','Sexta','Sabado','Domingo']

console.log(nomeDias[d.getDay()-1]);

Using toLocaleDateString

    let data = "20/10/2018";
    let dataArray = data.split("/");
    let d = dataArray[1] + '/' + dataArray[0] + '/' + dataArray[2];

    d = new Date(d);

let diaSemana = d.toLocaleDateString('pt-BR',{weekday: 'long'});
console.log(diaSemana);

Browser other questions tagged

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