How do I check if a string contains a valid year only... I've the classic way but it seems it works only with complete dates. Here's what I tried:
string MyString = "2001";
DateTime MyDateTime = DateTime.Parse(MyString);
Console.WriteLine(MyDateTime);
This code snippet throws an exception !
Any help would be appreciated.

Check if string contains valid year
Sobachatina
Amde
Hi
Or you can do like this :
Yours
Markku
jackline
My Version:
string MyString="1776";
Console.WriteLine(DateTime.ParseExact(MyString,"yyyy", CultureInfo.CurrentCulture));
jrx
Except for 0. There is no year 0.
Emadkb
Hi Raihan,
Your code throws an exception because 2001 isn't a valid date. It may be a valid year (you and I both know it is), but just isn't a valid date.
You could intialize a new datetime object and then use the AddYears method to add the number of years. The resulting date will be January 1st of year+1 (a new datetime intializes to 1/1/0001)
string MyString = "2001";
DateTime MyDate = new DateTime();
DateTime MyDate2 = MyDate.AddYears(int.Parse(MyString));
Console.WriteLine(MyDate2.ToString());
Please not that in the example above, int.Parse(MyString) will throw an exception if MyString doesn't contain a valid integer value. If you are using VS 2005 (.NET framework 2.0), you should use the int.TryParse() method. Otherwise you'll have to place the parsing of the integer in a try catch block.
Hope this helps,
blackmamba
What do you mean by "a valid year" Any integer is potentially a valid year.
If you mean a four-digit integer starting with 19 or 20 then you could use a regular expression:
if
(Regex.IsMatch(MyString, "^(19|20)[0-9][0-9]"))...
That can easily be adapted to stretch the rules of what constitutes a valid year.
If the year has to be between a minimum and a maximum, convert it to an integer and check it:
int year;if(int.TryParse(MyString, out year) && (year >= 1942 && year <= 2142))
...
HTH
Luc Pettett