Aantal dagen in een bepaalde maand ophalen met JavaScript?

Mogelijk duplicaat:
Wat is de beste manier om het aantal dagen in een maand te bepalen met javascript?

Stel dat ik de maand als een getal en een jaar heb.


Antwoord 1, autoriteit 100%

// Month in JavaScript is 0-indexed (January is 0, February is 1, etc), 
// but by using 0 as the day it will give us the last day of the prior
// month. So passing in 1 as the month number will return the last day
// of January, not February
function daysInMonth (month, year) {
    return new Date(year, month, 0).getDate();
}
// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29

Antwoord 2, autoriteit 19%

Date.prototype.monthDays= function(){
    var d= new Date(this.getFullYear(), this.getMonth()+1, 0);
    return d.getDate();
}

Antwoord 3, autoriteit 6%

Het volgende neemt elke geldige datetime-waarde en retourneert het aantal dagen in de bijbehorende maand… het elimineert de dubbelzinnigheid van beide andere antwoorden…

// pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
    return new Date(anyDateInMonth.getFullYear(), 
                    anyDateInMonth.getMonth()+1, 
                    0).getDate();}

Antwoord 4

Een andere mogelijke optie is het gebruik van Datejs

Dan kun je doen

Date.getDaysInMonth(2009, 9)     

Hoewel het toevoegen van een bibliotheek alleen voor deze functie overdreven is, is het altijd fijn om te weten welke opties je tot je beschikking hebt 🙂

Other episodes