I received the error 'The string was not recognized as a valid DateTime. There is an unknown word starting at index 17'
on a server when trying to convert a Date and Time string to a DateTime, but I had no such error in development or testing.
The string in question was "20 MAY 2019 10:37a.m."
.
I found that the problem was with the AM and PM designators on the server, they were set in the format of “AM” but all other servers where set to “a.m.”.
I could have logged a job for someone to change the setting on the server, but I wasn’t convinced that I wouldn’t get the problem when deploying to a different production server, so I decided to build the fix into the solution.
The Fix
The fix is to dynamically change the AM and PM designators in the culture.
Here is how I did it…
protected DateTime CombineDatetime(string date, string time)
{
// format for parsing
string dateTime = date + " " + time;
CultureInfo culture = CultureInfo.CreateSpecificCulture("en-NZ"); // or whatever you have
DateTimeStyles styles = DateTimeStyles.None;
// set the AM and PM designators based on the input style
if (dateTime.ToLower().Contains("a.m.") || dateTime.ToLower().Contains("p.m."))
{
culture.DateTimeFormat.AMDesignator = "a.m.";
culture.DateTimeFormat.PMDesignator = "p.m.";
}
else if (dateTime.ToLower().Contains("am") || dateTime.ToLower().Contains("pm"))
{
culture.DateTimeFormat.AMDesignator = "AM";
culture.DateTimeFormat.PMDesignator = "PM";
}
else
{
// must be 24 hour, so do nothing
}
DateTime tempDate;
if (!DateTime.TryParse(dateTime, culture, styles, out tempDate))
{ // this should never happen
return DateTime.MinValue;
}
return tempDate;
}