"Generic function to convert any type date to desired date format"
While working in a project, I got stuck in a issue in which I needed a generic function that converts the date string in any format to a desired date format.
The solution which I got is as follows:
public static string FormatDate(string input, string goalFormat, string[] formats)
{
var c = CultureInfo.CurrentCulture;
var s = DateTimeStyles.None;
var result = default(DateTime);
if (DateTime.TryParseExact(input, formats, c, s, out result))
return result.ToString(goalFormat);
throw new FormatException("Unhandled input format: " + input);
}
This is a generic method which will accept date string in any format and will convert it into the desired format.
Example of Usage:
var formats = new[] { "dd/MM/yy", "dd/MM/yyyy", "MM/dd/yy", "yyyy/MM/dd", "MM/dd/yyyy" };
string d = "27/06/2015";
string t = ClassName.FormatDate(d, "MM/dd/yyyy", formats);
The parameters you have to pass is the input string,Desired format,formats array(That will contain all the possible formats of the input date string).
Note:-> The format of the input string passed should must be mentioned inside the formats array.
Happy Coding...!
0 Comment(s)