c# – Check if day exists in month

Question:

I need to check/validate if a (numeric) day exists in a given month.

For example: I have the 31 day, and as it doesn't exist in the month of February, the condition will fail.

I think a simple if will solve the problem, where I build a date and check if it exists.

Answer:

You can find out what the last day of month 'x' is:

public bool IsDiaValido(int dia, int mes, int ano)
{
    int ultimoDiaMes = DateTime.DaysInMonth(ano, mes);
    if(dia > ultimoDiaMes || dia < 1)
        return false;
    else
       return true;
}

That way you don't need to put a try-catch, avoiding generating an error unnecessarily.

Scroll to Top