Giving System.FormatException: String was not recognized as a valid DateTime. using datetime.ParseExact in C#

Manoj Singh picture Manoj Singh · Feb 16, 2011 · Viewed 18k times · Source

I am below code in c#, where I am converting my string type format date to datetime, but giving the error.

if (!string.IsNullOrEmpty(SessionDictionary.GetValue("UserDetails", "ExpiryDate")))
{
    DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "dd mmm yy", null);                      
    strDate = sitedata.FormatDate(ExpiryDate, TridionDateFormat.ShortDate);
}
else
{
    strDate = "-";
}

My SessionDictionary.GetValue("UserDetails", "ExpiryDate") is string type data which returns "31/01/2011 00:00:00" format date, in above code where I am using DateTime.ParseExact it is giving me System.FormatException: String was not recognized as a valid DateTime. error.

Please suggest what is wrong.

Thanks.

Answer

Joe picture Joe · Feb 16, 2011

The sample date you describe (31/01/2011 00:00:00) looks like a format dd/MM/YYYY HH:mm:ss, so why are you using dd mmm yyyy?

Try

DateTime.ParseExact(..., "dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Note the use of HH (24-hour clock) rather than hh (12-hour clock), and the use of InvariantCulture because some cultures use separators other than slash.

For example, if the culture is de-DE, the format "dd/MM/yyyy" would expect period as a separator (31.01.2011).