I have created an extension method that I use everytime
public static DateTime? ToDateTime(this string dateTime)
{
if (string.IsNullOrEmpty(dateTime))
{
return null;
}
return DateTimeOffset.ParseExact(dateTime, new string[] { "MMM dd, yyyy", "dd/MM/yyyy", "d/M/yyyy", "dd-MM-yyyy", "d-M-yyyy", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-dd" }, CultureInfo.InvariantCulture).DateTime;
}
I have added multiple formats that I encounter in an array and I reuse this method every time, the above method works for the following examples of date:
- May 23, 2022
- 5-08-2023
- 05-08-2023
- 5/08/2023
- 05/08/2023
- 2023-02-01
- 2023-02-01T12:23:99Z
additionally in c# the answer of @Manjay can also be tried as follows :
char formatChar = '-';
if (dateTime.Contains('-'))
{
formatChar = '-';
}
if (dateTime.Contains('/'))
{
formatChar = '/';
}
string[] parts = dateTime.Split(formatChar);
var month = parts[0].PadLeft(2, '0');
var day = parts[1].PadLeft(2, '0');
var year = parts[2];
string properFormattedDate = $"{month}{formatChar}{day}{formatChar}{year}";
return DateTimeOffset.ParseExact(properFormattedDate, new string[] { "MMM dd, yyyy", "dd/MM/yyyy", "dd-MM-yyyy", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-dd" }, CultureInfo.InvariantCulture).DateTime;