[c#] 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?

This question is related to c# .net cultureinfo

The answer is


Try:

 DateTime.TryParseExact(txtStartDate.Text, formats, 
        System.Globalization.CultureInfo.InvariantCulture,
        System.Globalization.DateTimeStyles.None, out startDate)

Here you can check for couple of things.

  1. Date formats you are using correctly. You can provide more than one format for DateTime.TryParseExact. Check the complete list of formats, available here.
  2. CultureInfo.InvariantCulture which is more likely add problem. So instead of passing a NULL value or setting it to CultureInfo 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
    }
    

Try C# 7.0

var Dob= DateTime.TryParseExact(s: YourDateString,format: "yyyyMMdd",provider: null,style: 0,out var dt)
 ? dt : DateTime.Parse("1800-01-01");

string DemoLimit = "02/28/2018";
 string pattern = "MM/dd/yyyy";
 CultureInfo enUS = new CultureInfo("en-US"); 
 DateTime.TryParseExact(DemoLimit, pattern, enUS, 
                     DateTimeStyles.AdjustToUniversal, out datelimit);

For more https://msdn.microsoft.com/en-us/library/ms131044(v=vs.110).aspx


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.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to cultureinfo

DateTime and CultureInfo Find number of decimal places in decimal value regardless of culture how to set default culture info for entire c# application DateTime.TryParseExact() rejecting valid formats Get current language in CultureInfo Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy" How to use localization in C# Is there a way of setting culture for a whole application? All current threads and new threads?