Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is DateTime.TryParseExact in C# is not working as expected

Tags:

c#

When I try to run

DateTime.TryParseExact(employeeHireDate, "mm/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate);

C# is converting the DateTime to some other date that is 1/5/2015 where as im passing 05/05/2015.

Any help would be appreciated.

Following is my code:

static void Main(string[] args)
{
    string employeeHireDate = "05/05/2015";         
    DateTime dDate;
    var isDateValid= DateTime.TryParseExact(employeeHireDate, "m/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate);

    if (!isDateValid)
    {
        Console.WriteLine("Failed");
        Console.ReadLine();
    }
    else
    {
        Console.WriteLine("Success");
        Console.ReadLine();
    }
}
like image 318
Marshall Avatar asked Aug 31 '25 01:08

Marshall


2 Answers

Lower-case m in a format string is minutes. You want an upper-case M for months. Five minutes, with no month value specified, means you end up with the first month of the year. You need this instead:

DateTime.TryParseExact(employeeHireDate, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate);

Here's the reference:

https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings

like image 62
Joel Coehoorn Avatar answered Sep 02 '25 15:09

Joel Coehoorn


Use

DateTime.TryParseExact(employeeHireDate, "MM/dd/yyyy", 
    CultureInfo.InvariantCulture, DateTimeStyles.None, out dDate);

instead, with captial "MM". mm is for minutes, MM is for months (see documentation).

like image 24
René Vogt Avatar answered Sep 02 '25 14:09

René Vogt