ToDateTime
Gets a nullable DateTime object from a string input. Good for grabbing datetimes from user inputs, like textboxes and querystrings.
Source
public static DateTime? ToDateTime(this string s)
{
DateTime dtr;
var tryDtr = DateTime.TryParse(s, out dtr);
return (tryDtr) ? dtr : new DateTime?();
}
Example
// you can test the result like this:
var dt = TextBox1.Text.ToDateTime();
if (dt == null) {
throw new Exception("Your datetime was invalid");
}
else {
// this method takes a normal/non-nullable DateTime
// as its parameter.
DoSomething(dt.Value);
}