views:

780

answers:

4

I have a web server located in Switzerland and it is intended to serve both the American region and the European region. When a date is being displayed from the Americas, the date is separated by a period rather than a slash.

In some cases I want to user the period if they are European, in others I want to use the slash. If I specify the format string to use a slash, it will be converted to a period based on the computer settings. What do I need to do to specify the regional settings on a per user basis (the user has to log in and I do know what region he is coming from).

+1  A: 

Use a format string with DateTime.ToString(), like this:

 DateTime.Now.ToString("MM/dd/yyyy");

In this case, the / character means "use the date separator for the current culture.". Even better, you can just call DateTime.Now.ToShortDateString() to use the local system's short date format.

There's more help with localization in the System.Globalization namespace.

Now here's the trick: your 'local' system is your web server, and that means it's pretty much always going to use the Swiss format. So you also want to pass an IFormatProvider to tell the system what culture to use. That would look something like this:

DateTime.Now.ToString(System.Globalization.CultureInfo.GetCultureInfo("en-US"));
Joel Coehoorn
A: 

If the current culture uses the period as the date separator, then you can display with a slash using

C#

date.ToString(@"dd\/MM\/yyyy");

VB

date.ToString("dd\/MM\/yyyy")
Patrick McDonald
+3  A: 

Globalisation in ASP.NET should do everything for you pretty much. See this MSDN article, entitled How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization. This should be exactly what you want, as you simply need to set the current (UI) culture for the current thread when the user logs in. You can then call date.ToString() and it will return the text representation in the correct format.

Equivalently, you could do something like this:

var culture = System.Globalization.CultureInfo.GetCultureInfo("en-GB");
var dateString = date.ToString(culture.DateTimeFormat);

But it's really just doing the same thing manually, and is far less elegant. You might as well make use of the ASP.NET globalisation framework here.

Noldorin
+1  A: 

I've not had a need to use it but DateTime has built-in culture information that you could use:

DateTime dt = DateTime.Now;
dt.ToString(System.Globalization.CultureInfo.GetCultureInfo("fr-CH"));

See this at MSDN. Just record your user's culture ("fr-CH", "en-US", etc.) then you can do more than just USA v. Switzerland.

Alternatively I believe you can create your own culture information to format dates correctly, but again I've never had to do that.

Colin Burnett