Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override the default date separator in .net

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).

like image 879
Ross Goddard Avatar asked May 19 '09 12:05

Ross Goddard


3 Answers

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.

like image 195
Noldorin Avatar answered Sep 29 '22 21:09

Noldorin


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")
like image 23
Patrick McDonald Avatar answered Sep 29 '22 19:09

Patrick McDonald


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"));
like image 42
Joel Coehoorn Avatar answered Sep 29 '22 21:09

Joel Coehoorn