Returning the day of the week in Javascript

1

I have two codes to return the day of the week, but in the first it returns undefined, and in the second it returns the wrong day, for example on 22/05/2016 it returns Wednesday, and the correct one would be Sunday.

Code 1:

$(document).ready(function(){
    $("input#dataR").blur(function(){
        var data = $("#dataR").val();
        var teste = new Date(data);
        var dia = teste.getDay();
        var semana = new Array(6);
        semana[0]='Domingo';
        semana[1]='Segunda-Feira';
        semana[2]='Terça-Feira';
        semana[3]='Quarta-Feira';
        semana[4]='Quinta-Feira';
        semana[5]='Sexta-Feira';
        semana[6]='Sábado';
        alert(semana[dia]);
    });
});

Code 2:

$(document).ready(function(){
    $("input#dataR").blur(function(){
        var data = $("#dataR").val();
        var arr = data.split("/");
        var teste = new Date(arr[0],arr[1],arr[2]);
        var dia = teste.getDay();
        var semana = new Array(6);
        semana[0]='Domingo';
        semana[1]='Segunda-Feira';
        semana[2]='Terça-Feira';
        semana[3]='Quarta-Feira';
        semana[4]='Quinta-Feira';
        semana[5]='Sexta-Feira';
        semana[6]='Sábado';
        alert(semana[dia]);
    });
});
    
asked by anonymous 22.05.2016 / 19:38

1 answer

3

Creating Date objects with strings as '22/05/2016' is not a good idea. The best is as in your other example with .split('/') .

The problem that is escaping you here is that the months in JavaScript begin at 0 . In other words, January is the month 0 .

Note also that the Date constructor receives arguments in this order:

  

Year, Month, Day, Hour, Minute, Second

That said, you can do your code like this:

$(document).ready(function(){
    var semana = ["Domingo", "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado"];
    $("input#dataR").blur(function(){
        var data = this.value;
        var arr = data.split("/").reverse();
        var teste = new Date(arr[0], arr[1] - 1, arr[2]);
        var dia = teste.getDay();
        alert(semana[dia]);
    });
});

Example: link

    
22.05.2016 / 19:45