Q:

Convert string of date format to string of another date format

I want to convert a string of date format to a string with another format.
The string DateOfBirth could be in different formats such as:

01/15/2017
01-15-2017
1.15.2017
1.5.2017

I want to convert it to another pattern that I get it as parameter.
public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
}

Let's assume that date = "01/15/2017" and convertToDateFormat = "YYYY/MM/DD". How could I change it to the new format?
The problem for me was to do it generic so that it will accept any parametrs.
I thought that I can convert date to DateTime and then to use ToString with the format but can you offer any better idea?

A:

Parse to DateTime and then back to String:
public string ConvertStringDateFormat(string date, string convertToDateFormat) {
  return DateTime
    .ParseExact(date,
       new string[] { "M/d/yyyy", "M-d-yyyy", "M.d.yyyy" },
       CultureInfo.InvariantCulture, 
       DateTimeStyles.AssumeLocal)
    .ToString(convertToDateFormat); // convertToDateFormat = @"yyyy\/MM\/dd" for YYYY/MM/DD
}

A:

try this
public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
    return Convert.ToString(Convert.ToDateTime(date),convertToDateFormat);
}

