ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

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);
}

Author: Graham Peel

Submitted on: 6 dec. 2011

Language: C#

Type: System.DateTime

Views: 8260