views:

402

answers:

6

What's the best way to check if a string is a valid year using C#?

I currently have a dropdown list that contains the values {'All','2009','2008'} etc, and I want to know whether the selection is one of the dates or the 'All' field.

Currently I'm checking for bool isYearValid = (Year.ToLower() == "all") ? false : true;

How do I check whether the value is a valid year so that I don't have to have this hardcoded check for 'All'?

+6  A: 

Given that a year simply needs to be a valid number, you could just use int32.TryParse and then simply check the range based on what range you want the year to be in.

Deeksy
A: 

Wouldn't this be better anyway?

bool isYearValid = !string.Equals(Year, "all", StringComparison.OrdinalIgnoreCase);
David M
Given it's a hardcoded 'All' value, how he checks the case is probably not very important ;)
Ant
Yes, very true.
David M
A: 

your could use

DateTime DT
datetime.tryparse(string.format("1/1/{0}",Year),DT)
rerun
A: 

How about:

<asp:ListItem Value="1900" Text="All" />

That way you don't have to manually check for "All" at the validation point. You still need to check for 1900, when actually implementing this, but there'd definitely be now way to avoid making that a special scenario, anyway.

Other than that, DateTime.TryParse is the proper way to find out if a string representation is a valid date.

David Hedlund
+4  A: 

You can try parsing the year as an integer:

int iYear = 0;

if (Int.TryParse(Year, out iYear))
{
  //You have a valid year inside iYear
  //If you are not sure about the dropdown list values,
  //you can of course do more checks for validity. For example:
  //if iYear is in a proper range
}
Petros
A: 

Well, no-one's mentioned it, but why not have a symbol for 'All' defined somewhere and use that in both the drop down initialisation and the comparison?

JonB