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

ConvertToDateTimeNullable

ConvertToDateTimeNullable

Source

public static DateTime? ConvertToDateTimeNullable(this object textValue, string format = "")
{
    DateTime dateTimeValue;

    if (!string.IsNullOrWhiteSpace(format))
    { //if we a have format passed,parse using that format only
        if (DateTime.TryParseExact(textValue == null ? string.Empty : textValue.ToString(), format, System.Globalization.CultureInfo.InvariantCulture,
            System.Globalization.DateTimeStyles.None, out dateTimeValue))
        {
            return dateTimeValue;
        }
    }
    else
    {
        if (DateTime.TryParse(textValue == null ? string.Empty : textValue.ToString(), out dateTimeValue))
            return dateTimeValue;
    }
    return null;
}

Example

"".ConvertToDateTimeNullable();

Author: RK

Submitted on: 13 mei 2019

Language: C#

Type: ConvertToDateTimeNullable

Views: 633