I've got a class that contains two DateTime members.
When I try to assign a "human-readable" value representing a date to the DateTime member, though, it rejects it with the message, "String was not recognized as a valid DateTime."
The line of code that fails is:
md.BeginDate = DateTime.Parse(reader.GetValue(5).ToString());
In context, showing the value that I am trying to convert from a string representation of a DateTime:
Based on the 1st and accepted answer here [https://stackoverflow.com/questions/2193012/string-was-not-recognized-as-a-valid-datetime-format-dd-mm-yyyy], I also tried this:
md.BeginDate = DateTime.ParseExact(reader.GetValue(6).ToString(), "MM/dd/yyyy", null);
...but with the same ignominious result.
Based on this, I tried the following:
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "yyyy-MM-dd HH:mm:ss.ffffff";
. . .
DateTime.ParseExact(dateString, format, provider);
...but get the same result.
The value of "dateValAsStr" is 2021-01-21 11:25:56.9608384
It turns out it was a really dumb oversight on my part. When I stepped through it, I saw that the Date (TEXT) value in the database was empty. So this code "works" (doesn't throw an exception):
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "yyyy-MM-dd HH:mm:ss.fffffff";
. . .
string qry = "SELECT LocationName, Address1, City, StateOrSo, PostalCode, " +
"BeginDate, EndDate, MapDetailNotes, Latitude, Longitude " +
"FROM CartographerDetail " +
"WHERE FKMapName = @FKMapName";
. . .
dateValAsStr = reader.GetValue(5).ToString().Trim();
if (! String.IsNullOrWhiteSpace(dateValAsStr))
{
md.BeginDate = DateTime.ParseExact(dateValAsStr, format, provider).Date;
}
dateValAsStr = reader.GetValue(6).ToString().Trim();
if (!String.IsNullOrWhiteSpace(dateValAsStr))
{
md.EndDate = DateTime.ParseExact(dateValAsStr, format, provider).Date;
}
The simple example you give is this:
string dateString = "2021-01-21 11:25:56.9608384";
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "yyyy-MM-dd HH:mm:ss.fffffff";
DateTime result = DateTime.ParseExact(dateString, format, provider);
Note that the number of decimal places for the seconds is 7
, yet your format
only has 6
f
s.
If you change to 7
f
s then it works fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With