Doubt on how to use date object

Asked

Viewed 49 times

-1

<!DOCTYPE html>
<html>
<head>
<title>test2</title>
</head>
<script>
    var data = prompt("informe o numero do mês desejado: ");

    var mes =[
    "Janeiro",
    "Fevereiro",
    "Março",
    "Abril",
    "Maio",
    "Junho",
    "Julho",
    "Agosto",
    "Setembro",
    "Outubro",
    "Novembro",
    "Dezembro"];
    var mes= data.getMonth();

    console.log("Esse mes é "+mes);

</script>
</html>

In case I already managed to make the conversion of playing a number and bring a month, but I want to do it using the object date.

2 answers

1

You are not instantiating the variable to call the object Date(). Like the Date() does not write the months, but returns a numerical value, for example: The month of June is represented by the number 5.

You will have to make a repeat structure, the most recommended for this case, would be the switch follow the example:

var data = new Date();
var mes = data.getMonth();

switch (mes) {
    case 0:
        mes = 'Janeiro';
        break;
    case 1:
        mes = 'Fevereiro';
        break;
    case 2:
        mes = 'Março';
        break;
    case 3:
        mes = 'Abril';
        break;
    case 4:
        mes = 'Maio';
        break;
    case 5:
        mes = 'Junho';
        break;
    default:
        mes = 'Mês inválido';
}

alert('Nós estamos no mês de ' + mes);

That is, as the variable mes is picking up the current month (June), which is represented by the number 5, this variable will return us the number 5. According to our repetition structure, case the return of the variable mes is 5, the new variable value mes will be "June".

1

Use the method Date.prototype.toLocaleDateString() that returns a string with the representation of the date part based on the language.

const data = new Date();                         //Pega a data do sistema.

const mes = data.toLocaleDateString('pt-BR', {  //O retorno será em português do Brasil.
  month: 'long'                                 //Define que será retornado apenas o mês por extenso.
});

console.log("Esse mes é", mes);

Browser other questions tagged

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