C#

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.

I hope you guys found something useful. Please give your valuable feedback/comments/questions about this article. Please let me know how you like and understand this article and how I could improve it.

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago