Thomas
Thomas

Reputation: 34188

Getting number of days for a specific month

how could i programmatically detect, how many days are there for a particular month & year.

Upvotes: 23

Views: 31000

Answers (2)

Zano
Zano

Reputation: 2761

It's already there:

DateTime.DaysInMonth(int year, int month);

should do it.

Upvotes: 70

Paolo Tedesco
Paolo Tedesco

Reputation: 57172

Something like this should do what you want:

static int GetDaysInMonth(int year, int month) {
    DateTime dt1 = new DateTime(year, month, 1);
    DateTime dt2 = dt1.AddMonths(1);
    TimeSpan ts = dt2 - dt1;
    return (int)ts.TotalDays;
}

You get the first day of the month, add one month and count the days in between.

Upvotes: 4

Related Questions