Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c# - DateTime.Parse not reversing month and day based on thread culture

I'm parsing a date string from a database so that I can display it in the current culture of the UI thread. For some reason, the date is not parsing with respect to the culture - specifically, I'm parsing a en-US date to switch to a es-ES date and the month/day positions are not switching.

According to this MSDN article I should just be able to use Parse with only the date string as a parameter. I should also be able to explicitly provide a culture object. Neither works and my date remains as mm/dd instead of dd/mm. I've verified that both the thread's CurrentCulture and CurrentUICulture are set properly and if I do a new DateTime, that outputs correctly.

Am I missing something?

EDIT: Nothing fancy in the code, just the .NET API.

CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
DateTime formattedDate = DateTime.Parse("5/9/2014");
formattedDate.ToShortDateString(); //this returns 5/9/2014
DateTime.Today.ToShortDateString(); //this returns 9/5/2014
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem you are having is that 5/9/2014 is a perfectly valid month string in either dd/mm/yyyy or mm/dd/yyyy format so when you do DateTime.Parse("5/9/2014") it will successfully parse it as 5th September 2014 (since the es-es date format is dd/mm/yyyy).

This then explains why when you output you get something different to DateTime.Today (which is obviously 9th May).

A working version of your program would be:

var outputCulture = CultureInfo.CreateSpecificCulture("es-es");
var inputCulture = CultureInfo.CreateSpecificCulture("en-us");
Thread.CurrentThread.CurrentCulture = outputCulture;
Thread.CurrentThread.CurrentUICulture = outputCulture;
DateTime formattedDate = DateTime.Parse("5/9/2014", inputCulture);
Console.WriteLine(formattedDate.ToShortDateString()); //this returns 09/05/2014
Console.WriteLine(DateTime.Today.ToShortDateString()); //this returns 09/05/2014

As you see I am specifying the culture for input so that it knows to use the en-us culture rather than the explicitly set es-es culture for parsing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...