Subscribe Us

LightBlog

Sunday, 21 February 2021

Convert Any String Date Format To Common Date Format In C#

In this post, we will see how we can accept any date format and return with a common date format with the TryParseExact() method. Converting date to the wanted date format is a time spending and slow process in several languages including C#.

TryParseExact includes the following overload methods

DateTime.TryParseExact(string value, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result)

Value: It is a string representation of a date.

Format: It is a format specifier that specifies a date look like after conversion.

Provider: It is an object which specifies culture info.

style: It is an enum DateTimeStyles.

result: return formatted date.

In the below code, I created one method namely ChangeDateFormat which accepts string date in any format and will return with fix format i.e. “MM/dd/yyyy” format.

public string ChangeDateFormat(string inputDate)

{

    string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy",  "d/MM/yyyy",

                     "dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy", "MM/dd/yyyy",

                         "yyyy/MM/dd","dd/MM/yyyy","MM-dd-yyyy","yyyyMMdd"

                         };

    DateTime.TryParseExact(inputDate, formats,

    System.Globalization.CultureInfo.InvariantCulture,

    System.Globalization.DateTimeStyles.None, out DateTime outputDate);

    return outputDate.ToString("MM/dd/yyyy");

}

In the above method need to pass all possible format in string[] which we wanna accept. we have done now you can use this method anywhere in your project.

No comments:

Post a Comment