Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParseExact returns false

Tags:

c#

.net

I'm trying to parse 4/27/2011 12:00:00 AM using M/d/yyyy H:m:s a pattern, invariant culture and default options but it doesn't parse.

I'll be very thankful if someone will help me to realize what's wrong.

like image 403
lua.rasta Avatar asked Dec 07 '22 10:12

lua.rasta


1 Answers

Your pattern doesn't include tt, which is the AM/PM designator and is in your input text. Additionally, you want h for 12-hour clock rather than 24 for 24-hour clock, and it looks like you will always have two-digit minutes and seconds, so you probably just want a pattern of M/d/yyyy h:mm:ss tt.

Sample code which works:

using System;
using System.Globalization;

class Test
{
    static void Main()
    {
        DateTime value;
        if (DateTime.TryParseExact("4/27/2011 12:00:00 AM",
                                   "M/d/yyyy h:mm:ss tt",
                                   CultureInfo.InvariantCulture,
                                   DateTimeStyles.None,
                                   out value))
        {
            Console.WriteLine(value);
        }
    }
}

See MSDN for more information on custom date and time format strings.

like image 124
Jon Skeet Avatar answered Dec 10 '22 03:12

Jon Skeet