How many days is the current month with Javascript?

Asked

Viewed 3,579 times

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.

3 answers

5


function diasNoMes(mes, ano) {
    var data = new Date(ano, mes, 0);
    return data.getDate();
}

// Exemplo:
console.log(diasNoMes(2, 2017)); // Exibe 28.
  • 3

    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.

  • 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 use var data = new Date(ano, mes + 1, 0); instead.

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());

  • I believe that if you use the Ideone or the Repl.it to display your working codes will get better results. If it is only HTML/CSS/JS, you can use the Stack Overflow tool itself.

  • Thanks Anderson Carlos Woss, I haven’t figured out how to do it yet, I’m new!

  • 1

    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

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