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

18.3k views Asked by At

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.

4

There are 4 answers

0
Joe On BEST ANSWER

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

1
Cheng Chen On

Probably because of mmm(there isn't such month format), try MMM instead.(looks like Feb/Jan/etc)

1
Yogesh On

You are using the wrong format to parse the date. The correct one is:

DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "dd/MM/yyyy hh:mm:ss", null)

Also, if your system date format is set to dd/MM/yyyy you can simply use:

DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "G", null)
0
Louis Waweru On

Try DateTime ExpiryDate = DateTime.ParseExact(SessionDictionary.GetValue("UserDetails", "ExpiryDate"), "g", null);

or see here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx