Month with two digits in getMonth, but giving error

Asked

Viewed 600 times

0

I’m trying to put double digits on getMonth, but it’s going wrong. What I’m doing wrong?

var data = new Date();
var dia = ("0" + data.getDate()).slice(-2);
var mes = ("0" + (data.getMonth() + 1)).slice(-2);
var ano4 = data.getFullYear();
var hora = ("0" + data.getHours()).slice(-2);
var min = ("0" + data.getMinutes()).slice(-2);
var str_data = dia + '/' + (mes + 1) + '/' + ano4;
var str_hora = hora + ':' + min;

console.log(str_data + " " + str_hora);

  • 2

    I didn’t get that (mes + 1)... is concatenating the month + the number 1. Maybe it should just be mes, thus: var str_data = dia + '/' + mes + '/' + ano4;

  • @Sam Err that same...rsrs Thank you.

  • Maybe your code can be more effective using https://momentjs.com/

1 answer

2


You are concatenating the variable string mes with the number 1 in this section:

var str_data = dia + '/' + (mes + 1) + '/' + ano4;

Note that on this line the variable mes is a string:

var mes = ("0" + (data.getMonth() + 1)).slice(-2);

The correct would be to use only mes and not mes + 1:

var str_data = dia + '/' + mes + '/' + ano4;

Code:

var data = new Date();
var dia = ("0" + data.getDate()).slice(-2);
var mes = ("0" + (data.getMonth() + 1)).slice(-2);
var ano4 = data.getFullYear();
var hora = ("0" + data.getHours()).slice(-2);
var min = ("0" + data.getMinutes()).slice(-2);
var str_data = dia + '/' + mes + '/' + ano4;
var str_hora = hora + ':' + min;

console.log(str_data + " " + str_hora);

Browser other questions tagged

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