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
returns
true
for Isdiavalido(-1, 12, 2014);– Andre Figueiredo
I changed the code, by @Andréfigueiredo
– IPValverde
I know some people don’t like it, but it’s so much easier to do:
return dia >= 1 && dia <= DateTime.DaysInMonth(ano, mes)
.– Maniero
Also prefer, I only left this way to be clearer. I hate to do if-It to return a boleano.
– IPValverde
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.
– Bacco