Alois
Alois

Reputation: 36

C# TryParseExact CultureInfo.InvariantCulture Changing behavior when culture change

I am trying to convert date with the following format "d/MM/yyyy"

example :

  • 5/11/2014
  • 12/12/2013
  • 31/01/2012

I am using TryParseExact method :

private const string DateFormat = "d/MM/yyyy";
Culture = CultureInfo.InvariantCulture;
DateTime creationDateConverted;
DateTime.TryParseExact(creationDate, DateFormat, Culture, 
            DateTimeStyles.None, out creationDateConverted);

The display method is :

@Html.DisplayFor(m => object.date)

date having :  DisplayFormat( DataFormatString="{0:d/MM/yyyy}")

The server which host the website has a US culture.

if I set the culture to fr-FR using Web.config it works well.

But if I don't set that culture it does not work, it convert it do MM/dd/yyyy format and of course some date don't pass with that format.

I don't understand why the culture would have influence on that method because I provide a specific format and a culture invariant.

I also tried to provide a Culture fr-Fr to the method but no luck

EDIT : when I say fail, I means that the TryParseExact Method return false

Upvotes: 0

Views: 458

Answers (2)

Jodrell
Jodrell

Reputation: 35706

The parsing code you have posted is unaffected by any external culture setting.

However, the culture could effect what happens when you interrogate the value of the DateTime creationDateConverted.

Upvotes: 0

Plue
Plue

Reputation: 1790

DateTime has no format. And the ToString method output depend on the culture.

If you want a specific format use this :

creationDateConverted.ToString("d/MM/yyyy");

Upvotes: 3

Related Questions