I am trying to convert different string date formats to a specific format i.e., YYYYMMDD and all the incoming dates are valid. How can I return a new list of strings representing this format
-
for dates there's DateTime type in C#. and here you can find how to convert it to string with formattingba-a-aton– ba-a-aton2021-06-09 12:56:01 +00:00Commented Jun 9, 2021 at 12:56
-
2A date 3/4/2000 could be a third of April or a fourth of March. Without additional hints it is impossible to know for sure which is it.Dialecticus– Dialecticus2021-06-09 12:56:16 +00:00Commented Jun 9, 2021 at 12:56
-
Why do you want to convert it to a list of strings? A better choice would be to parse the input list into a list of DateTime instances. Types exist for a reason.Igor– Igor2021-06-09 12:58:01 +00:00Commented Jun 9, 2021 at 12:58
Add a comment
|
2 Answers
Use DateTime.Parse() to get the date/time information into a standard DateTime object and then you can output it any way that you like.
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parse?view=net-5.0
Comments
public static List<string> TransformDateFormat(List<string> dates)
{
var formats = new string[]
{
"yyyy/MM/dd",
"dd/MM/yyyy",
"MM-dd-yyyy",
"yyyyMMdd"
};
return dates
.Select(date => DateTime.ParseExact(date, formats, null).ToString("yyyyMMdd"))
.ToList();
}
You must specify all possible formats.