I'm getting a string back from my page and I want to make sure it's a date. This is what I have so far (it works) and I just want to know if this is the "best" way to do it. I'm using .NET 4.
int TheMonth =0;
int TheDay = 0;
int TheYear = 0;
DateTime NewDate;
var TheIncomingParam = Request.Params.Get("__EVENTARGUMENT").ToString();
char[] TheBreak = { '/' };
string[] TheOutput = TheIncomingParam.Split(TheBreak);
try { TheMonth = Convert.ToInt32(TheOutput[0]); }
catch { }
try { TheDay = Convert.ToInt32(TheOutput[1]); }
catch { }
try { TheYear = Convert.ToInt32(TheOutput[2]); }
catch { }
if (TheMonth!=0 && TheDay!=0 && TheYear!=0)
{
try { NewDate = new DateTime(TheYear, TheMonth, TheDay); }
catch { var NoDate = true; }
}
Use one of the Parse
methods defined on the DateTime
structure.
These will throw an exception if the string is not parseable, so you may want to use one of the TryParse
methods instead (not as pretty - they require an out parameter, but are safer):
DateTime myDate;
if(DateTime.TryParse(dateString,
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out myDate))
{
// Use myDate here, since it parsed successfully
}
If you know the exact format of the passed in date, you can try using the ParseExact
or TryParseExact
that take date and time format strings (standard or custom) when trying to parse the date string.
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