I cannot deserialise a datetime string from Excel using EPPlus. I have read other answers about this but still cannot this to work and get the error: String 'M-d-yy hh:mm' was not recognized as a valid DateTime.
As per other answers a found on this topic, I have changed the DateTimeFormat to "M/d/yy hh:mm", which is what EPPlus is returning as a string when I put a watch on it. My current culture is "en-UK", however I'm using InvariantCulture because EPPlus is out-putting the above format which I would rather use. If this is an issue then I don't mind changing it but I don't see the point of going from a US format to a UK format, only for it be changed again to an international ISO format in the DB.
It must still somehow think that it follows a UK datetime format but I can't see where I'm going wrong. Any help would be greatly appreciated! Thanks
Here is what I have at the moment:
var dateTimeConverter = new IsoDateTimeConverter
{
Culture = CultureInfo.InvariantCulture,
DateTimeFormat = "M/d/yy h:mm",
DateTimeStyles = DateTimeStyles.AssumeLocal
};
var excelImportResponse = new ExcelImportResponse<T>();
foreach (DataRow row in dataTable.AsEnumerable())
{
excelImportResponse.Objects.Add(
JsonConvert.DeserializeObject<T>(
new JObject(
row.Table.Columns
.Cast<DataColumn>()
.Select(c => new JProperty(c.ColumnName.Trim(), JToken.FromObject(row[c])))
)
.ToString(Formatting.None),
new JsonSerializerSettings
{
Error = delegate (object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
{
excelImportResponse.Errors.Add(args.ErrorContext.Error.Message);
args.ErrorContext.Handled = true;
},
Converters = { dateTimeConverter }
})
);
}
The error: String '7/1/20 14:15' was not recognized as a valid DateTime.
Full exception
at System.DateTimeParse.ParseExact(ReadOnlySpan1 s, ReadOnlySpan
1 format, DateTimeFormatInfo dtfi, DateTimeStyles style)
at System.DateTime.ParseExact(String s, String format, IFormatProvider provider, DateTimeStyles style)
at Newtonsoft.Json.Converters.IsoDateTimeConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)