Вопрос

I have a code that looks like code below in a PC which runs fine:

DateTime.Parse("10/10/2012");

I copied it over to other machine and it says something blaming the date conversion is wrong. What I had to do to work around it is to use:

DateTime.TryParseExact("10/10/2012", "dd/MM/yyyy", null);

Does anyone know if there is any configuration in c# or the machine that control this such things? (or it might be .net version different between the two computers? but i am pretty sure they are the same in both machine as I used Ms Visual Studio 2008 for both machine).

I am talking about global configuration on windows itself that makes some strict exceptions to my programs. Anyone knows about this?

Это было полезно?

Решение

(You're mixing ParseExact and TryParseExact.)

The differences come from the CultureInfo.CurrentCulture.Different parts of the world write dates in different ways.

Even saying ParseExact("10/10/2012", "dd/MM/yyyy", null) can be problematic. Have you tried first setting

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("da-DK");

and then doing the above ParseExact? It will fail because the DateSeparator is not "/" in this culture. To fix it, either say

DateTime.ParseExact("10/10/2012", @"dd\/MM\/yyyy", null)

or say

DateTime.ParseExact("10/10/2012", "dd/MM/yyyy", CultureInfo.InvariantCulture)

The first works by "escaping" the slash / so it becomes a literal slash and is not translated to the current DateSeparator. The second one works by giving the invariant culture where we know that the DateSeparator is indeed "/".

Addition:

If you never set CurrentCulture in your code, its value depends on the Regional and language settings of your operating system. I suppose you're running Windows? Details might depend on exact Windows version.

Другие советы

The system's current culture is used when parsing dates. I would bet that the two machines have different cultures.

If your input is always the same (say en-us format) and you want to abstract away from user date&time formatting preferences then DateTime.TryParseExact is a good, proper way to go.

You can try this to set cultural invariant date time:-

 using System.Globalization;
//...
 DateTime _datetime = DateTime.Now;
string _formattedDateTime = _datetime.ToUniversalTime().ToString("s", 
DateTimeFormatInfo.InvariantInfo) + "Z";
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top