DateTime.TryParseExact() rejecting valid formats
This is the Simple method, Use ParseExact
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime result;
String dateString = "Sun 08 Jun 2013 8:30 AM -06:00";
String format = "ddd dd MMM yyyy h:mm tt zzz";
result = DateTime.ParseExact(dateString, format, provider);
This should work for you.
Try:
DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate)
Here you can check for couple of things.
- Date formats you are using correctly. You can provide more than one format for
DateTime.TryParseExact
. Check the complete list of formats, available here. CultureInfo.InvariantCulture
which is more likely add problem. So instead of passing aNULL
value or setting it toCultureInfo provider = new CultureInfo("en-US")
, you may write it like. .if (!DateTime.TryParseExact(txtStartDate.Text, formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out startDate)) { //your condition fail code goes here return false; } else { //success code }