Skip to content

Localizing Web Apps: Dates & Numbers

In desktop apps, you can use Xojo.Core.Locale to get the user’s locale for formatting dates and numbers. However, in a web app this value returns the locale used by the web server rather than the locale of the current user session.

To display dates formatted in the locale of the user session, you need to get the LanguageCode from WebSession and use that to create a locale that you can then use to display the date.

This code (in a WebLabel Shown event handler) gets the language code for the user session and then uses it to display the current date:

Dim langCode As Text = Session.LanguageCode.DefineEncoding(Encodings.UTF8).ToText
Dim locale As New Xojo.Core.Locale(langCode)
Me.Text = Xojo.Core.Date.Now.ToText(locale, _
  Xojo.Core.Date.FormatStyles.Long, _
  Xojo.Core.Date.FormatStyles.None)

When the browser is set to English, this displays: January 9, 2017

When it is set to French, this displays: 9 janvier 2017

Use the same technique with number formatting. This code (in a WebLabel Shown event handler) gets the language code for the user session and then uses it to display a formatted number:

Dim langCode As Text = Session.LanguageCode.DefineEncoding(Encodings.UTF8).ToText
Dim locale As New Xojo.Core.Locale(langCode)
Dim num As Double = 1234.56
Me.Text = num.ToText(locale, "#,###.##")

When the browser is set to English, the number displays like this: 1,234.56

When it is set to French, it displays like this: 1 234,56

To get both the language and region information, you should check the value of the “Accept-Language” HTTP header:

Dim langHeader As String = Session.Header("Accept-Language")

Which returns both the language and region code in a format like this: en-US.

Note that there may be more than one value returned in this header so you may need to parse it to ensure you get the value you actually want.

Refer to Localization in the User Guide for more information on how to localize your desktop, iOS and web apps.