Reputation: 9063
I am having trouble with the parsing of a string value in date Time format.
This is the method where the parsing of the date time format takes place.
internal static DateTime ParseDateTime(string dateTimeString, string[] formats)
{
try
{
DateTime dateStamp = DateTime.ParseExact(dateTimeString,
formats, CultureInfo.CurrentCulture, DateTimeStyles.None);
return dateStamp;
}
catch (Exception exe)
{
var message = $"dateTimeString: '{dateTimeString}', '{string.Join(",", formats)}'.";
Utility.log(message);
throw;
}
}
The formats I am passing in looks like this.
public static string[] DateTimeFormats => new string[]
{
"dd-MM-yyyy",
"MM/dd/yyyy",
"dd/MM/yyyy",
"M/d/yyyy",
"d.M.yyyy",
"dd.MM.yyyy",
"MM/dd/yyyy",
"M/d/yyyy",
"yyyy/MM/dd",
"dd-MM-yyyy HH:mm tt"
};
I logged the exception and this is the value that results in the error.
'20-06-2017 12:00 AM'
What am I missing? Kind regards
Upvotes: 0
Views: 83
Reputation: 82534
As I wrote in my comment (and to be fair, Jon Skeet wrote before me), "dd-MM-yyyy HH:mm tt"
should be "dd-MM-yyyy hh:mm tt"
.
The HH
format string is for hours using a 24-hour clock, while
The hh
format string is for hours using a 12-hour clock.
However, I think you have a bigger issue here, and that is you might parse some strings wrong.
You have in your format array some formats that are interchangeable for some dates - Any date where the day is less than 13 can be parsed with either "MM/dd/yyyy"
or "dd/MM/yyyy"
- meaning that 01/02/2018
might be January second 2018 or February 1st 2018.
Upvotes: 3