0

I inherited code like following:

System.DateTime dateTimeOut;
if(DateTime.TryParse("18/06/2015", out dateTimeOut))
{
  Console.WriteLine("Good Job!");
}

"Good Job!" is never printed out. From MSDN I found that DateTime.TryParse uses the DateTime format from System.Globalization.DateTimeFormatInfo.CurrentInfo which in turn is from Thread.CurrentThread.CurrentCulture.DateTimeFormat. And in my system it is "mm/dd/yyyy" - that's why "18/06/2015" cannot be parsed.

Then I went to Control Panel and changed DateTime format to "dd/mm/yyyy" and restarted my PC. But when I run the program again, Thread.CurrentThread.CurrentCulture.DateTimeFormat is still "mm/dd/yyyy"....I am wondering who controls this setting and where I can change it?

sean717
  • 11,759
  • 20
  • 66
  • 90
  • 1
    Or you can use `DateTime.TryParseExact` with explicit format, remember, lower case `mm` is for minutes, you need `MM` *(upper case)* for month – Habib Jun 19 '15 at 16:53
  • 1
    You'd probably have to change your current culture, not just your date time format settings, since the date time format is coming from the culture. You could always pass in an IFormatProvider to tryparse to specify what date format you want it to parse. – PilotBob Jun 19 '15 at 16:55
  • 1
    You can set `CurrentCulture` by code, for example: `Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("de");` – Flat Eric Jun 19 '15 at 16:56
  • I checked and the current culture is "en-ca" – sean717 Jun 19 '15 at 16:56

2 Answers2

2

Specify your culture:

System.DateTime dateTimeOut;
var culture = CultureInfo.CreateSpecificCulture("en-GB");
var styles = DateTimeStyles.None;
if (DateTime.TryParse("18/06/2015", culture, styles, out dateTimeOut))
{
  Console.WriteLine("Good Job!");
}

Good Job is sent to the console here.

PilotBob
  • 3,107
  • 7
  • 35
  • 52
1

You can use the overload of DateTime.TryParse which accepts an IFormat Provider:

public static bool DateTime.TryParse(string s,
    IFormatProvider provider,
    DateTimeStyles styles,
    out DateTime result
)

Your code becomes:

System.DateTime dateTimeOut;
if(DateTime.TryParse("18/06/2015", new CultureInfo("it-IT"), DateTimeStyles.None, out dateTimeOut))
{
  Console.WriteLine("Good Job!");
}

it-IT is just an example of a culture which uses dd/MM/yyyy time format. you should use the one appropriated for you.

Or you can use the accepted answer of this question, from Austin, to change the culture of the entire App Domain:

In .NET 4.5, you can use the CultureInfo.DefaultThreadCurrentCulture property to change the culture of an AppDomain.

For versions prior to 4.5 you have to use reflection to manipulate the culture of an AppDomain. There is a private static field on CultureInfo (m_userDefaultCulture in .NET 2.0 mscorlib, s_userDefaultCulture in .NET 4.0 mscorlib) that controls what CurrentCulture returns if a thread has not set that property on itself.

Community
  • 1
  • 1
Ortiga
  • 8,455
  • 5
  • 42
  • 71