Parsing "dd MMMM, yyyy" using DateTime.TryParseExact

128 views Asked by At

I'm working with TryParseExact but it's throwing an error. What could be the issue? Thanks

DateTime result;

if (DateTime.TryParseExact("31 December, 2023", ["'dd MMMM, yyyy'"],
                           CultureInfo.InvariantCulture,
                           DateTimeStyles.None, out result))
{
    // Success
}
else 
{
    // Failure
}

I've tried escaping the date format as "dd MMMM',' yyyy" and using DateTimeStyles.AdjustToUniversal but there's no effect.

1

There are 1 answers

2
Joel Coehoorn On
When you see the `Exact` in `TryParseExact()`, **it means it**; the method is _super strict_ about the input _exactly matching_ the specified format.~~

In this case, the single quotes in this string are part of the expected format:

'dd MMMM, yyyy'

To match this format, the date would need to look like this:

'31 December, 2023'
You probably want to use this format string instead:
dd MMMM, yyyy

Finally, I know it's probably just an example, but if you really have a constant value you're also generally better off using the DateTime constructor, like this:

DateTime result = new(2023, 12, 31);

or this, if you're not yet comfortable with the newer syntax:

var result = new DateTime(2023, 12, 31);