JavaScript Date: trovare l’ultimo giorno del mese e gestire gli anni bisestili
Per trovare il numero dell’ultimo giorno del mese, usa new Date(year, monthIndex + 1, 0).getDate(). Leggi year e monthIndex dallo stesso oggetto Date con getFullYear() e getMonth(). Il calcolo include febbraio negli anni bisestili e il cambio di anno dopo dicembre.
Perché il giorno zero del mese successivo dà l’ultimo giorno
In new Date(year, monthIndex, day), gennaio ha indice 0 e dicembre ha indice 11. Impostare day a 0 significa tornare indietro di un giorno dal primo del mese indicato. Il giorno zero di marzo 2024 è quindi il 29 febbraio. Per dicembre si usa l’indice 12, che passa a gennaio dell’anno successivo. ECMAScript · Date Constructor
const last = new Date(2024, 2, 0);
console.log(last.getFullYear(), last.getMonth() + 1, last.getDate()); // 2024 2 29
Trovare l’ultimo giorno del mese corrente
Leggi l’ora corrente una sola volta e ricava anno e mese dallo stesso oggetto, così corrispondono allo stesso istante anche al cambio del mese. Il codice sceglie il mese corrente nel fuso locale dell’ambiente. getDate() restituisce un numero tra 28 e 31. Per il mese corrente in UTC, passa now.getUTCFullYear() e now.getUTCMonth() + 1 alla funzione qui sotto.
const now = new Date();
const year = now.getFullYear();
const monthIndex = now.getMonth();
const lastDay = new Date(year, monthIndex + 1, 0).getDate();
console.log(lastDay);
Calcolare da anno e mese
La funzione accetta anni da 1 a 9999 e mesi da 1 a 12. Il numero del mese, passato senza modifiche, seleziona quello seguente nella data UTC. Per esempio, il valore 2 per febbraio è l’indice di marzo, e il giorno zero dà la fine di febbraio. Il costruttore new Date() con più argomenti trasforma gli anni 0–99 in 1900–1999. setUTCFullYear() mantiene l’anno indicato, mentre getUTCDate() legge il risultato indipendentemente dal fuso locale. ECMAScript · Date.prototype.setUTCFullYear()
function lastDayOfMonth(year, month1to12) {
if (!Number.isInteger(year) || year < 1 || year > 9999 ||
!Number.isInteger(month1to12) || month1to12 < 1 || month1to12 > 12) {
throw new RangeError();
}
const date = new Date(0);
date.setUTCFullYear(year, month1to12, 0);
return date.getUTCDate();
}
console.log(lastDayOfMonth(2024, 2)); // 29
console.log(lastDayOfMonth(2023, 2)); // 28
console.log(lastDayOfMonth(2024, 12)); // 31
console.log(lastDayOfMonth(96, 2)); // 29
Un anno è bisestile se è divisibile per 4. Se è divisibile per 100, deve essere divisibile anche per 400. Febbraio ha quindi 28 giorni nel 1900 e 29 nel 2000. Ha 29 giorni anche nell’anno 0096. Date tiene già conto di questa regola. ECMAScript · Day Number and Time within Day
Provare l’esempio completo
Salva il codice come last-day.html e aprilo nel browser. All’inizio mostra anno, mese e ultimo giorno secondo il fuso locale. Inserisci l’anno 2024 e il mese 2 e seleziona Calcola. Il risultato è 2024-02-29. Febbraio 2023 dà 2023-02-28 e dicembre 2024 dà 2024-12-31. Se inserisci 0 o 13, il browser segnala che il mese è fuori intervallo.
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Calcolare l’ultimo giorno di un mese</title>
</head>
<body>
<h1>Calcolare l’ultimo giorno di un mese</h1>
<form id="month-form">
<label>Anno <input id="year" name="year" type="number" min="1" max="9999" step="1" required></label>
<label>Mese <input id="month" name="month" type="number" min="1" max="12" step="1" required></label>
<button type="submit">Calcola</button>
</form>
<p>Ultimo giorno <output id="result" for="year month"></output></p>
<script>
function lastDayOfMonth(year, month1to12) {
if (!Number.isInteger(year) || year < 1 || year > 9999 ||
!Number.isInteger(month1to12) || month1to12 < 1 || month1to12 > 12) {
throw new RangeError();
}
const date = new Date(0);
date.setUTCFullYear(year, month1to12, 0);
return date.getUTCDate();
}
const form = document.querySelector('#month-form');
const yearInput = form.elements.namedItem('year');
const monthInput = form.elements.namedItem('month');
const result = document.querySelector('#result');
const now = new Date();
function showLastDay() {
const year = yearInput.valueAsNumber;
const month = monthInput.valueAsNumber;
const day = lastDayOfMonth(year, month);
const pad = (value, length) => String(value).padStart(length, '0');
result.textContent = [pad(year, 4), pad(month, 2), pad(day, 2)].join('-');
}
yearInput.value = now.getFullYear();
monthInput.value = now.getMonth() + 1;
if (form.checkValidity()) showLastDay();
form.addEventListener('submit', event => {
event.preventDefault();
if (form.reportValidity()) showLastDay();
});
</script>
</body>
</html>




