1
I would like to know how many days is the current month with Javascript, for example with PHP, I would do so:
Date('t');
Very simple with PHP, but with Javascript there is some easy way?
obs. I use Angularjs if it helps in anything.
1
I would like to know how many days is the current month with Javascript, for example with PHP, I would do so:
Date('t');
Very simple with PHP, but with Javascript there is some easy way?
obs. I use Angularjs if it helps in anything.
5
function diasNoMes(mes, ano) {
var data = new Date(ano, mes, 0);
return data.getDate();
}
// Exemplo:
console.log(diasNoMes(2, 2017)); // Exibe 28.
4
function _numDias(){
var objData = new Date(),
numAno = objData.getFullYear(),
numMes = objData.getMonth()+1,
numDias = new Date(numAno, numMes, 0).getDate();
return numDias;
}
console.log(_numDias());
2
Returns the number of days of the current month. This month of February 2017 returns 28. Month of March 31 and so on. February Mayors Bison Return 29.
Date.prototype.diasNoCorrenteMes = function() {
var days = [30, 31],
m = this.getMonth();
if (m == 1) {
return ( (this.getFullYear() % 4 == 0) && ( (this.getFullYear() % 100 != 0 ) || (this.getFullYear() % 400 == 0) ) ) ? 29 : 28;
} else {
return days[(m + (m < 7 ? 1 : 0)) % 2];
}
}
var myDate = new Date();
console.log(myDate.diasNoCorrenteMes());
Thanks Anderson Carlos Woss, I haven’t figured out how to do it yet, I’m new!
There is an error there, multiple years of 100 are not leap, unless there are multiples of 400 as well. Just doing %4 is not enough.
https://pt.wikipedia.org/wiki/Ano_bissexto#Algoritmo_de_determina.C3.A7.C3.A3o
Bacco in 2100 we will all be in heaven, rs. Is that correct? Return this.getFullYear() %4 == 0 && this.getFullYear() %100 != 0 || this.getFullYear() % 400 == 0 ? 29 : 28;
Browser other questions tagged javascript
You are not signed in. Login or sign up in order to post.
It worked because in JS the 2 is the third month, and you took the last day of the previous month. Need to be careful with this, if the person use with other JS functions that return the month based on zero.
– Bacco
As @Bacco said, it’s good to be careful when using with a month generated by the method
Date().getMonth();
. If so, the scheme is to usevar data = new Date(ano, mes + 1, 0);
instead.– Nary Luiz