Check if day exists in month

Asked

Viewed 2,480 times

11

I need to verify/validate if a (numerical) day exists in a given month.

For example, I have the day 31, and as it does not 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.

5 answers

17


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

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;
}

This way you don’t need to place a Try-catch, avoiding unnecessarily generating an error.

  • returns true for Isdiavalido(-1, 12, 2014);

  • 1

    I changed the code, by @Andréfigueiredo

  • 7

    I know some people don’t like it, but it’s so much easier to do: return dia >= 1 && dia <= DateTime.DaysInMonth(ano, mes).

  • 1

    Also prefer, I only left this way to be clearer. I hate to do if-It to return a boleano.

  • 1

    Not that I am against making the code clear, but in practice many people copy it as it is, and end up "enshrining" this type of code. I think it is more interesting to do the "technical" form, and explain in the text what is happening (but it is only my humble opinion). However, +1 is given.

4

I don’t know if it’s the best way, but the way I do it is:

try
{
    var test = Convert.ToDateTime("31/02/2014");
}
catch (FormatException)
{
    // Não existe a data
}
  • If performance is at stake, capturing an exception in this way can be costly. Other than that, it works, so +1.

4

A simple Datetime.Tryparse or Datetime.Parse whether the date proposed in string is a valid date already taking into account the different days of each leap month and years:

public bool isValidDate(string value) {
    DateTime result;
    return DateTime.TryParse(value, out result);
}

Overload:

public bool isValidDate(int dia, int mes, int ano) {
    try {
        return DateTime.Parse(dia + "/" + mes + "/" + ano) > DateTime.MinValue;
    } catch { }
    return false;
}

And other variants...

A Try/catch is required for anomalous cases such as day = 0 or day 32, what is possible or any exception that will happen. In the case of Tryparse it is not necessary because Try/catch is already embedded in the function.

Tests successfully performed:

c.isValidDate(null);        // false
c.isValidDate("");          // false
c.isValidDate("       ");       // false

c.isValidDate("31/01/2014");    // true
c.isValidDate("28/02/2014");    // true
c.isValidDate("29/02/2012");    // true
c.isValidDate("29/02/2014");    // false
c.isValidDate("-29/02/2014");   // false
c.isValidDate("29/0/2014");     // false

c.isValidDate(31, 01, 2014);    // true
c.isValidDate(28, 02, 2014);    // true
c.isValidDate(29, 02, 2012);    // true
c.isValidDate(29, 02, 2014);    // false

c.isValidDate(-1, 02, 2014);    // false
c.isValidDate(31, 01, -1);      // false
c.isValidDate(15, 0, 2014);     // false
c.isValidDate(99, 99, 9999);    // false
c.isValidDate(01, 01, 0001);    // true

4

I decided to respond to not enshrine a redundant form of code. I am also giving option to Overload for a string with the date.

public bool EhDiaValido(int dia, int mes, int ano) {
    return dia >= DateTime.MinValue && dia <= DateTime.DaysInMonth(ano, mes);
}

public bool EhDiaValido(string data) {
    DateTime resultado;
    return DateTime.TryParse(data, out resultado);
}

In C# 7 the last method can be written as:

public bool EhDiaValido(string data) {
    return DateTime.TryParse(data, out var resultado);
}

I put in the Github for future reference.

1

Simple, try to create the date and see if it fails:

DateTime dia;
try {
  dia = new DateTime(year: 2014, month: 02, day: 31);
} catch (ArgumentOutOfRangeException ex) {
  // A data não existe, tratar
}

Little job:

static bool DataExiste(int ano, int mes, int dia) {
  try {
    new DateTime(ano, mes, dia);
    return true;
  } catch (ArgumentOutOfRangeException) { }

  return false;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.