Get number of days in a Month

  • Thread starter Thread starter Ronald Celis
  • Start date Start date
R

Ronald Celis

Hi,

is there anyway to get the Number of days in a given month and Year in C#

thanks

Ronald Celis
 
This is exactly what you're looking for:

System.DateTime.DaysInMonth(int year, int month)

JER
 
Wow, I didn't know that was there. ARGH.

I guess I can throw this messy thing out:

public static int GetDaysInMonth(int month, int year)
{
if (month < 1 || month > 12)
{
throw new System.ArgumentOutOfRangeException("month", month, "month must
be between 1 and 12");
}
if (1 == month || 3 == month || 5 == month || 7 == month || 8 == month ||
10 == month || 12 == month)
{
return 31;
}
else if (2 == month)
{
// Check for leap year
if (0 == (year % 4))
{
// If date is divisible by 400, it's a leap year.
// Otherwise, if it's divisible by 100 it's not.
if (0 == (year % 400))
{
return 29;
}
else if (0 == (year % 100))
{
return 28;
}

// Divisible by 4 but not by 100 or 400
// so it leaps
return 29;
}
// Not a leap year
return 28;
}
return 30;
}


Pete
 
Pete Davis said:
Wow, I didn't know that was there. ARGH.

I guess I can throw this messy thing out:

else if (2 == month)

<snip>

You can also throw out the above "messy" syntax, assuming you don't
actually prefer it in terms of readability to:

if (month==2)

which I believe most people do. Unlike C++, it's safe to do the above
as a typo of

if (month=2)

is caught by the compiler, as the type of the expression in an if
statement must be boolean.
 
Back
Top