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

NullDateToString

Prints out a nullable datetime's value (if its not null) in the string format specified as a parameter. A final parameter is specified for what to print if the nullable datetime was, in fact, null.

Source

public static string NullDateToString(this DateTime? dt, string format = "M/d/yyyy", string nullResult = "")
{
     if (dt.HasValue)
         return dt.Value.ToString(format);
     else
         return nullResult;
}

Example

var nullableDate = GetDateWhichCouldBeNull();
Response.Write(nullableDate.NullDateToString("mm/dd/yy", "-no date found-"));

Author: Graham Peel

Submitted on: 6 dec. 2011

Language: C#

Type: System.DateTime

Views: 5711