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

ToString

returns a formatted string on a nullable date

Source

/// <summary>
/// Returns a formatted date or emtpy string
/// </summary>
/// <param name="t">DateTime instance or null</param>
/// <param name="format">datetime formatstring </param>
/// <returns></returns>
public static string ToString(this DateTime? t, string format)
{
    if (t != null)
    {
        return t.Value.ToString(format);
    }

    return "";
}

Example

DateTime? dt = null;

string s = dt.ToString("yyyy-MM-dd");  //s = ""

dt =  DateTime.Now;

s = dt.ToString("yyy-MM-dd"); //s = "2007-31-12"

Author: C.F.Meijers

Submitted on: 11 dec. 2007

Language: C#

Type: System.DateTime

Views: 6626