Converting a date format string to a different date format string

I want to convert a date format string to a string with a different format.

DateOfBirth string can be in different formats, such as:

  • 01/15/2017
  • 01-15-2017
  • 01/05/2017
  • 2017/05/2017

I want to convert it to another template, which I get as a parameter.

public string ConvertStringDateFormat(string date, string convertToDateFormat)
{
}

Suppose date = "01/15/2017" and convertToDateFormat = "YYYY / MM / DD". How can I change it to a new format?

The problem for me was to make it common so that it accepts any parameters.

I thought I could convert the date to DateTime and then use ToString in the format, but can you suggest a better idea?

+4
source share
3 answers

try it

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

DateTime, 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
}
+4

, :

   (Convert.ToDateTime(date)).ToString(convertToDateFormat)
+2
source

Source: https://habr.com/ru/post/1662535/


All Articles