Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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

like image 365
Kinyanjui Kamau Avatar asked Dec 04 '22 19:12

Kinyanjui Kamau


1 Answers

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

string todaysDate = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
like image 170
Mark Byers Avatar answered Dec 07 '22 08:12

Mark Byers