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:
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?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With