Incomprehensible DateTime behavior

I created a C # WinForms application.

The following works on my computer:

DateTime.ParseExact("13/05/2012", "dd/mm/yyyy", null) 

but this is not so:

 DateTime.Parse("13/05/2012") 

On my client computers, this has changed. It works:

 DateTime.Parse("13/05/2012") 

but this is not so:

 DateTime.ParseExact("13/05/2012", "dd/mm/yyyy", null) 

Error:

 String was not recognized as a valid DateTime. 

Could not find any information on the Internet about this issue. The program uses .Net Framework 4 and is an x86 application. I am running Windows 8 x64, the client is running Windows 7 x64.

Does anyone know why this is happening?

Thanks.

+6
source share
2 answers

The reason you get different behavior on different computers is because they work with different cultures. Try running this line of code on both computers to see if it outputs something else: (ideone)

 System.Console.WriteLine(CultureInfo.CurrentCulture); 

Output (example):

  en-US

Culture defines many things, one of which is the date separator. If you want consistent behavior for all users, try specifying a culture: (ideone)

 CultureInfo cultureInfo = CultureInfo.InvariantCulture; // or whatever you prefer DateTime dateTime = DateTime.ParseExact("13/05/2012", "dd/MM/yyyy", cultureInfo); 

The above code assumes that you have the following statements:

 using System; using System.Globalization; 
+12
source

Be careful; in custom date and time format strings , the mm specifier represents "minutes" rather than "months". You should use mm for several months.

 DateTime.ParseExact("13/05/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture) 
+11
source

Source: https://habr.com/ru/post/916034/


All Articles