Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime.TryParseExact only working in "One Way"

Scope:

I have been trying to develop a super-tolerant DateTime.Parse routine, so I decided to give most "widely-used" formats a try to better understand the format masks.

Problem:

I have defined a specific format (String) which I use as myDate.ToString(format), and it works wonders. The problem is, If I get this same String (result of the .ToString(format) operation), and feed it back to DateTime.TryParseExact (...) it fails.

Code / Test:

System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;

// Defining Format and Testing it via "DateTime.ToString(format)"
string format = "MM/dd/yyyy HH:mm:ss tt"; 
string dtNow  = DateTime.Now.ToString (format);
Console.WriteLine (dtNow);

// Trying to Parse DateTime on the same Format defined Above
DateTime time;
if (DateTime.TryParseExact (dtNow, format, provider,    System.Globalization.DateTimeStyles.None, out time))
{
    // If TryParseExact Worked
    Console.WriteLine ("Result: " + time.ToString ());  
}
else
{
    // If TryParseExact Failed
    Console.WriteLine ("Failed to Parse Date");
}

Output is : "Failed to Parse Date".

Question:

Why can I use the format string to format a certain date as text, but I can't use the same format to feed the string back to a date object ?

EDIT:

I have added part of my method to this example, and I would like to know why the "ParseDate" method fails to return a proper date, given that the "String" is in the right format.

like image 308
Marcello Grechi Lins Avatar asked May 04 '15 12:05

Marcello Grechi Lins


1 Answers

Since you use DateTime.ToString() method without any IFormatProvider, this method will use your CurrentCulture settings.

That's why your

string dtNow  = DateTime.Now.ToString (format);

line might generate a different string representation than MM/dd/yyyy HH:mm:ss tt format.

Three things can cause this issue;

  • Your CurrentCulture has a different DateSeparator than /
  • Your CurrentCulture has a different TimeSeparator than :
  • Your CurrentCulture has a different or empty string as a AMDesignator and/or PMDesignator

Since you try to parse your string with provider (which is InvariantCulture) on your DateTime.TryParseExact method, generate your string based on that provider as well.

string dtNow  = DateTime.Now.ToString(format, provider);

You told your CurrentCulture is pt-BR and this culture has empty string "" as a AMDesignator and PMDesignator. That's why your dtNow string will not have any AM or PM designator on it's representation part.

Here a demonstration.

like image 75
Soner Gönül Avatar answered Nov 08 '22 18:11

Soner Gönül