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

Anjum Riwi

Parse the string in exact data format with null check

Source

/// <summary>
/// Parse Exact with using your date format 
/// </summary>
/// <param name="date">string</param>
/// <param name="dateFormat">"dd/MM/yyyy" Or "dd/MM/yy" etc.</param>
/// <returns>DateTime</returns>
public static DateTime ToSafeParseExact(this string date, string dateFormat = "dd/MM/yyyy")
{
    date = date.ToNonNullString();
    return string.IsNullOrWhiteSpace(date) ? default(DateTime) : DateTime.ParseExact(date, dateFormat, CultureInfo.InvariantCulture);
}

Example

e.g 1: with default format

string StartSearchDate = "30112015"; //30th Nov 2015 

var startSearchDate = StartSearchDate.ToSafeParseExact();


e.g 2: with explicitly passing date format

string StartSearchDate = "11302015"; //30th Nov 2015 
var startSearchDate = StartSearchDate.ToSafeParseExact(), "MM/dd/yyyy");

Author: Anjum Rizwi

Submitted on: 30 nov 2015

Language: C#

Type: System.String

Views: 2109