简体   繁体   中英

DateTime.ParseExact String not recognized as valid datetime

After having spent long hours trying various suggestions found here in SO as well as through out google, I turn the SO community.

I have an Asp.Net project that read data from a Database into poco classes. I cannot convert a string value representing a DateTime into the appropriate value in c#. Here is my code:

string value = get_value_from_repository(fieldname, repository); 
// value = "21/1/2015 12:00:00 πμ" which means 21-jan-2015 12:00:00 am (greek)

DateTime.ParseExact(value, "dd/M/yyyy h:mm:ss tt",CultureInfo.InvariantCulture, DateTimeStyles.None);

No matter what format I try to use ("dd/M/yyyy h:mm:ss tt", "d/M/yyyy hh:mm:ss tt", "dd/M/yyyy HH:mm:ss tt") I still get this error. Any suggestion toward the right direction would be greatly appreciated. Thank you.

You're passing in Invariant culture, which would not recognise the Greek characters for "am" - that's my guess. Try a Greek CultureInfo object instead (possibly CurrentCulture if it's set correctly).

You can use the greek DateTimeFormat :

var greek = new CultureInfo("el-GR").DateTimeFormat;
DateTime dt = DateTime.ParseExact(date, "dd/M/yyyy h:mm:ss tt", greek, DateTimeStyles.None);

This works as expected and returns 21-jan-2015. If the greek DateSeparator would not be / you also need to use '/' instead since / are replaced with the localized date separator .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM