So I'm trying to figure out if there is another kind of way to check if a date is valid. So the idea is that if the date is valid then it continue's using the given date, if the date is invalid is uses the date of today.
This is what I got at the moment:
public void setBirthdate(int year, int month, int day)
{
if (month < 1 || month > 12 || day < 1 || day > DateTime.DaysInMonth(year, month))
{
Birthdate = DateTime.Today;
}
else
Birthdate = new DateTime(year, month, day);
}
So is there any shorter/more readable way of doing this?
Thanks in advance
You could use the values to try constructing a valid DateTime
, then catch the ArgumentOutOfRangeException
that occurs if the arguments are out of range:
public void setBirthdate(int year, int month, int day)
{
try
{
Birthdate = new DateTime(year, month, day);
}
catch (ArgumentOutOfRangeException)
{
Birthdate = DateTime.Today;
}
}
Some may disagree with using exceptions like this, but I'm just letting the DateTime
class do its own checks, instead of recreating them myself.
From the documentation, an ArgumentOutOfRangeException
occurs if:
Alternatively, you could copy the logic from the DateTime
class: (reference)
public void setBirthdate(int year, int month, int day)
{
if (year >= 1 && year <= 9999 && month >= 1 && month <= 12)
{
int[] days = DateTime.IsLeapYear(year)
? new[] { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}
: new[] { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
if (day >= 1 && day <= days[month] - days[month - 1])
Birthdate = new DateTime(year, month, day);
}
else
Birthdate = DateTime.Today;
}
I would use the TryParse
(MSDN) method over exception catching (which can be high overhead if called frequently with invalid values):
DateTime date;
if (DateTime.TryParse(string.Format("{0}-{1}-{2}", year, month, day), out date))
{
// Date was valid.
// date variable now contains a value.
}
else
{
// Date is not valid, default to today.
date = DateTime.Today;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With