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


Gets a nullable DateTime object from a string input. Good for grabbing datetimes from user inputs, like textboxes and querystrings.


public static DateTime? ToDateTime(this string s)
    DateTime dtr;
    var tryDtr = DateTime.TryParse(s, out dtr);
    return (tryDtr) ? dtr : new DateTime?();


// 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.

Author: Graham Peel

Submitted on: 6 dec 2011

Language: C#

Type: System.DateTime

Views: 8019