0

I have a problem stringifying dates in various cultures. Some time ago I posted a question on SO about it (C# DateTime ToString Standard culture format) and I implemented the solution posted there. But it's not working on Portuguese (for example) because ShortDatePattern is not equals than "d" predefined format:

CultureInfo ci = CultureInfo.GetSpecificCulture("pt-PT");
DateTime date = new DateTime(2019, 7, 26);
date.ToString("d", ci); // --> 26-07-2019
date.ToString(ci.DateTimeFormat.ShortDatePattern, ci); // --> 26/07/2019

How can I get the real format of a predefined style. I've seen the .Net source code of datetime.cs, and I can't understand how it works because following code "d" uses "ShortDatePattern" (https://referencesource.microsoft.com/#mscorlib/system/globalization/datetimeformat.cs,f4cacf1a27a6de16).

And I think that it depends on the machine that runs the code, because in some environments the "d" and ShortDatePattern is the same...

Marc
  • 1,359
  • 1
  • 15
  • 39
  • 1
    Both lines return the same string – Pavel Anikhouski Jul 26 '19 at 09:13
  • I get `26/07/2019` on both lines as well, but I'm running from Xamarin Studio on macOS. Maybe `System.Globalization` has different CultureInfo data on different platforms? – AlwaysLearning Jul 26 '19 at 09:32
  • Are you sure about that "GetSpecificCulture"? I had to use either `CultureInfo.CreateSpecificCulture("pt-PT")` or `new CultureInfo("pt-PT")` (on LinqPad) (and both returned two "26/07/2019" values) – Hans Kesting Jul 26 '19 at 10:10
  • @HansKesting I've found the response, I must use CreateSpecificCulture as you points... on my computer, it uses dashes as separator, but returns the same (using CreateSpecificCulture). – Marc Jul 26 '19 at 10:15

1 Answers1

0

Sorry, I've found my problem, in my real code I was using GetCultureInfo, however when I write the code on the question (by heart) I've used CreateSpecificCulture. So, I've modified the question to match with the real code and now I write the answer to leave here if anyone has a similar problem.

To solve the problem above I must use CreateSpecificCulture:

CultureInfo ci = CultureInfo.CreateSpecificCulture("pt-PT");
DateTime date = new DateTime(2019, 7, 26);
date.ToString("d", ci); // --> 26-07-2019
date.ToString(ci.DateTimeFormat.ShortDatePattern, ci); // --> 26-07-2019

More info about differences between CreateSpecificCulture and GetCultureInfo: When to use CultureInfo.GetCultureInfo(String) or CultureInfo.CreateSpecificCulture(String)

Marc
  • 1,359
  • 1
  • 15
  • 39