I need to know if a given string is a valid DateTime format string because the string may represent other things. I tried DateTime.ParseExact(somedate.ToString(format), format) thinking it would barf on an invalid format, but it doesn’t.
So I’m good with simply testing if the string contains only “yYmMdDsShH” characters. Something like std::string.find_first_not_of would work, but System.String doesn’t have this.
I thought that RegEx might do the trick, but I’m very weak with regular expressions.
Note that Linq is not available for this one (.NET 2.0 only).
Updated
To clarify, I need to know if a given string represents a date time format and not something else like this:
if (input == "some special value")
... // it's a special case value
else if (Environment.GetEnvironmentVariable(input))
... // it's an environment variable name
else if (IsDateTimeFormatString(input))
... // it's a date time format string
else if (input.IndexOfAny(Path.GetInvalidPathChars()) < 0)
... // it's a file path
else
throw new Exception(); // Not a valid input
I can restrict a DateTime format string to only “yYmMdDsShH”, or I can add a few separator characters into it as well, it’s up to me what to allow or not allow.
With .NET2, you need to roll your own check for this. For example, the following method uses a foreach to check:
If you had the option of using .NET 3.5 and LINQ, you could use Enumerable.Contains to work with characters directly, and Enumerable.All. This would simplify the above to: