Reputation: 56
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!
Upvotes: 0
Views: 336
Reputation: 27599
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.
Upvotes: 1
Reputation: 125610
/
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);
Upvotes: 0
Reputation: 222522
var dateString = "28/06/2012 06:04:10 PM";
DateTime dt = DateTime.ParseExact(dateString, "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
Upvotes: 0