Kinyanjui Kamau Kinyanjui Kamau - 1 year ago 117
C# Question

C# error "String was not recognized as a valid DateTime"

I am trying to save the DateTime.Now in the format "yyyyMMdd"

I have this code

string todaysDate = DateTime.Now.ToString();


U_Date_of_PD_added = GetDateFromString(todaysDate)

// U_Date_of_PD_added is a datetime Database field


//Method to get date from string
private DateTime GetDateFromString(string dateString)
string format = "yyyyMMdd";
return DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);

I keep getting the error "String was not recognized as a valid DateTime." as it tries to parse. What could be wrong?

I do not care if it saves the time, I would prefer 00:00:00.000

Answer Source

You also need to give the format string when you convert the date to a string:

string todaysDate = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download