简体   繁体   中英

Convert String to DateTime in C# - String was not recognized as a valid DateTime

I reviewed the question here: Convert string to datetime in C#.net

The format I'm trying to pass is only slightly different, but cannot get it to work.

My code:

var date = DateTime.ParseExact(@"28/06/2012 06:04:10 PM", @"dd/MM/yyyy hh:mm:ss tt", null);

So then I tried the example code from the question mentioned above:

var date = DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", null);

That doesn't work either. Both give me

System.FormatException
String was not recognized as a valid DateTime.

Any ideas would be greatly appreciated! Thanks!

The problem is localisation.

Consider these three statements:

DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", new CultureInfo("fr-fr"))
DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", new CultureInfo("en"))
DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", CultureInfo.InvariantCulture)

The first will not work whereas the last two will. In this case it is because the PM is not valid in fr-fr . If you try this:

DateTime.ParseExact(@"14/04/2010 10:14:49.", @"dd/MM/yyyy hh:mm:ss.tt", new CultureInfo("fr-fr"))

it will work fine.

As has been noted in comments other cultures may fail on other items. en-za uses a different date separator causing that to fail.

var dateString = "28/06/2012 06:04:10 PM";
DateTime dt = DateTime.ParseExact(dateString, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);

/ is date separator and probably in your culture it's not exactly / . The same issue can occur with : , which is replaced with current culture time separator. Try escaping both / and : :

var date = DateTime.ParseExact(@"28/06/2012 06:04:10 PM", @"dd\/MM\/yyyy hh\:mm\:ss tt", null);

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