Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert Stringified Date Value in format Month/Day/Year Time as a DateTime?

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:

enter image description here

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.

UPDATE

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

UPDATE 2

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;
}
like image 835
B. Clay Shannon-B. Crow Raven Avatar asked Dec 31 '22 17:12

B. Clay Shannon-B. Crow Raven


1 Answers

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 fs.

If you change to 7 fs then it works fine.

like image 131
Enigmativity Avatar answered Jan 02 '23 05:01

Enigmativity