C# DateTime conversion same culture on different m

2019-08-02 20:42发布

问题:

If i run this console app from my test italian machine:

static void Main(string[] args)
    {
        String date = DateTime.Now.ToString("yyyy-MM-dd HH:mm", new CultureInfo("it-IT"));
        Console.WriteLine(date);
        Console.ReadKey();
        CultureInfo ci = new CultureInfo("it-IT");
                Console.WriteLine("Time: " + ci.Name + " " + ci.DateTimeFormat.TimeSeparator);
                Console.WriteLine("Date: " + ci.Name + " " + ci.DateTimeFormat.DateSeparator);
        Console.ReadKey();
    }

displays:

2013-07-25 15:40 Time: it-IT : Date: it-It /

but if I run this code from my usa server:

2013-07-25 15.40 Time: it-IT . Date: it-It /

Why different format separator for the time part? The correct one for italian must be :

回答1:

You found out yourself that the data for the time separator for Italian changed between versions of Windows (colon is the more up-to-date version). This is expected as we are improving our data. If you found this because of transferring data between machines, you should be using standard invariant formats (like ISO 8601) that will be immune to data changes.



回答2:

I just run into this problem. Sometime I think that the problem is because there is an user override.

I suggest to load the CultureInfo using:

CultureInfo ci = new CultureInfo("it-IT", false);

Specify false as the useUserOverride parameter force to bypass any user settings.

In any case there is a change between Win8 and Win7. Running the code below (.NET 4.5):

CultureInfo ci = new CultureInfo("it-IT", false);

String date = DateTime.Now.ToString(ci);
Console.WriteLine(date);
Console.WriteLine("Time Separator: " + ci.DateTimeFormat.TimeSeparator);
Console.WriteLine("Date Separaotr: " + ci.DateTimeFormat.DateSeparator);
Console.ReadKey();

On Win 7 produce:

29/10/2013 14:12:33
Time Separator: :
Date Separaotr: /

while running it on Win 8 produce:

29/10/2013 15.08.43
Time Separator: .
Date Separaotr: /


回答3:

Replace

    ci.DateTimeFormat.TimeSeparator

with

    DateTimeFormatInfo.CurrentInfo.TimeSeparator;