Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to to convert date string of any format to a desired date format

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 177
    Comment on it

    "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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: