Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string of date format to string of another date format

Tags:

c#

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?

like image 314
Misha Zaslavsky Avatar asked Mar 10 '23 12:03

Misha Zaslavsky


1 Answers

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
}
like image 148
Dmitry Bychenko Avatar answered May 10 '23 04:05

Dmitry Bychenko