Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParseExact() rejecting valid formats

I'm parsing a DateTime value in an ASP.NET WebForms page and the date string keeps getting rejected by the DateTime.TryParseExact() method even though it clearly matches one of the supplied format strings.

It seems to fail on my development machine at home but work on the production server, so I am thinking of local date settings being involved, but this error occurs even when I supply an IFormatProvider (CultureInfo) object as a parameter

Here's the code:

DateTime startDate; string[] formats = { "dd/MM/yyyy", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",                     "dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy"};  var errStart = row.FindControl("errStartDate"); //my date format error message if (!DateTime.TryParseExact(txtStartDate.Text, formats, null, DateTimeStyles.None, out startDate)) {     errStart.Visible = true; //we get here even with a string like "20/08/2012"     return false; } else {     errStart.Visible = false; } 

Note I'm giving a null FormatProvider in the above, but the same problem occurs when I provide a CultureInfo object as (CultureInfo provider = new CultureInfo("en-US")) for this parameter.

What am I missing?

like image 318
see sharper Avatar asked Aug 17 '12 04:08

see sharper


Video Answer


1 Answers

Try:

 DateTime.TryParseExact(txtStartDate.Text, formats,          System.Globalization.CultureInfo.InvariantCulture,         System.Globalization.DateTimeStyles.None, out startDate) 
like image 66
Adil Mammadov Avatar answered Oct 23 '22 04:10

Adil Mammadov