Return the day of the week in Javascript

Asked

Viewed 10,981 times

1

I have two codes to return the day of the week, but the first returns undefined, and the second returns the wrong day, for example on 22/05/2016 returns Wednesday, and the correct 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]);
    });
});
  • 2

    In your second case, you are passing as parameters to the constructor of Date the values of day, month, year, but the order is the opposite (year, month, day). And note that in JS the months start from 0 (0 = January, 1 = February, ...)

  • @carlosfigueira I saw now your comment after putting the answer. Basically saying the same as you. Next you can put answer soon :)

1 answer

3


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

The problem you’re missing here is that the Javascript months start at 0. In other words, January is the month 0.

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

Year, Month, Day, Hour, Minute, Second

That said you can make 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: https://jsfiddle.net/nzcoxtar/

  • That’s right, man, thanks for your help!

Browser other questions tagged

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