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

StackOverflow https://stackoverflow.com/questions/5013308

Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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

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)

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

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top