DaysInMonth: calcolare il numero di “days” del “Month”

Era da tempo che non utilizzavo il metodo DaysInMonth ed ieri sera mi è tornato alla mente proprio durante un caso pratico.

La necessità era molto semplice: programmare una queque su Azure Function da una data fornita in ingresso al fine mese.

Per farlo è possibile ricorrere al seguente e semplice giochetto, ma non è la soluzione migliore:

  • Vado al primo del mese successivo

  • Aggiungo “-1” giorno

  • Prendo Days ed ho il mio risultato

1
2
3
4
5
6
7
8

private int GetDaysInMonthValue(DateTime dateTimeInput)
        {
            DateTime dateTimeNextMonth = new DateTime(dateTimeInput.Year, dateTimeInput.Month + 1, 1);
            dateTimeNextMonth = dateTimeNextMonth.AddDays(-1);
            return dateTimeNextMonth.Day;
        }

DaysInMonth: Firma ed Utilizzo

La classe DateTime espone il metodo DaysInMonth e guardando la sua firma possiamo capire quanto è semplice da usare

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

//
// Riepilogo:
// Returns the number of days in the specified month and year.
//
// Parametri:
// year:
// The year.
//
// month:
// The month (a number ranging from 1 to 12).
//
// Valori restituiti:
// The number of days in month for the specified year. For example, if month equals
// 2 for February, the return value is 28 or 29 depending upon whether year is a
// leap year.
//
// Eccezioni:
// T:System.ArgumentOutOfRangeException:
// month is less than 1 or greater than 12. -or- year is less than 1 or greater
// than 9999.
public static int DaysInMonth(int year, int month);

Sicuramente impiegherete più tempo a leggere tutte le righe sopra che a provarlo. Ora -da bravi- andiamo a modificare l’esempio precedente e trasformiamo le tre righe di codice in una solamente. Come? Ecco la risposta … DateTime.DaysInMonth - HowTo

1
2
3
4
5
6
7
8

        private int GetDaysInMonthValue(DateTime dateTimeInput)
        {
            return DateTime.DaysInMonth(
                dateTimeInput.Year, 
                dateTimeInput.Month);
        }

Come potete notare utilizzare DateTime.DaysInMonth è davvero semplice e non dovete preoccuparvi di nulla. Preoccuparvi di cosa? Ad esempio se il mese di Febbraio è bisestile oppure no.

Esiste anche l’alternativa -che purtroppo ho visto scritta in una classe- di uno switch o “if a catena” sul numero del mese. Ecco, se il vostro codice è di quello stile, vi consiglio vivamente di cambiarlo.

Happy Coding ^^

MDSN: DateTime.DaysInMonth(Int32, Int32) Method