B4A Library AHLocale library

With this library you can convert dates, timestamps, numbers and normal texts to the format your device uses. You can even translate your apps to different languages.

The AHLocale object provides many information about your devices locale settings like Currency symbol, month names, weekday names etc.

The AHTranslator object provides methods for creating multilanguage apps.

The AHDateTime object provides methods for formatting and parsing date strings. The internal DateTime object of B4A has the problem that it uses localized format identifier so it is not possible to parse a date string in the format "2011/05/19 12:15 AM" on a german device because the "AM" is "vorm." on it. With the AHDateTime object you can parse and format dates in any locale.

The AHTimeZone object provides methods to get information about timezones (like offset to UTC, DST offset etc.)

The AHDateUtils object provides methods to format dates and date ranges and display them localized.

The AHNumeric object provides methods to handle different (localized) number formats.

The example app starts always in english. Translation files for german, italian and japanese are provided. Try to select another language with the topmost spinner and see how the language of the user interface changes.

AHLocale
Author:
Markus Stipp
Version: 1.16
  • AHDateTime
    Fields:
    • DEFAULT As Int
    • FULL As Int
    • LONG As Int
    • MEDIUM As Int
    • SHORT As Int
    Methods:
    • Format (ticks As Long) As String
      Formats the specified ticks value to a string with the specified pattern.
    • GetDefaultDatePattern (Style As Int) As String
      Gets the default DatePattern of the device default locale

      Style - Use constants SHORT, MEDIUM, LONG, FULL, DEFAULT
    • GetDefaultDatePattern2 (Style As Int, Locale As AHLocale) As String
      Gets the default DatePattern of given locale

      Style - Use constants SHORT, MEDIUM, LONG, FULL, DEFAULT
      Locale - Reference to an AHLocale object
    • GetDefaultDateTimePattern (DateStyle As Int, TimeStyle As Int) As String
      Gets the device default DateTimePattern

      DateStyle - Style for Date
      TimeStyle - Style for Time
    • GetDefaultDateTimePattern2 (DateStyle As Int, TimeStyle As Int, Locale As AHLocale) As String
      Gets the DateTimePattern for the given Locale

      DateStyle - Style for Date
      TimeStyle - Style for Time
    • GetDefaultTimePattern (Style As Int) As String
      Gets the default TimePattern of the device default locale

      Style - Use constants SHORT, MEDIUM, LONG, FULL, DEFAULT
    • GetDefaultTimePattern2 (Style As Int, Locale As AHLocale) As String
      Gets the default TimePattern of given locale

      Style - Use constants SHORT, MEDIUM, LONG, FULL, DEFAULT
      Locale - Reference to an AHLocale object
    • GetShortDatePatternWithoutYear As String
      Return a short date pattern without year information
    • Initialize
      Initializes the AHDateTime object with the default locale.
    • Initialize2 (locale As AHLocale)
      Initializes the AHDateTime object with the given AHLocale object
    • InitializeUS
      Initializes the AHDateTime object with the <strong>en_US</strong> locale.
    • Parse (date As String) As Long
      Parses the specified string and returns a tick value.

      Throws an exception if the string can not be parsed.
    • is24HourFormat As Boolean
      Returns true if the user preference settings is 24 hour format.
    Properties:
    • Lenient As Boolean
      If you set this to true the parser is not very strict on his date format.
    • Pattern As String
      Sets or gets the Date/Time pattern

      Default pattern is: <strong>yyyy-MM-dd HH:mm:ss</strong>

      For allowed placeholders look here: <link>SimpleDateFormat|http://developer.android.com/reference/java/text/SimpleDateFormat.html</link>
    • TimeZone As AHTimezone
      Sets or gets the timezone for the AHDateTime object
  • AHDateUtils
    Fields:
    • FORMAT_12HOUR As Int
    • FORMAT_24HOUR As Int
    • FORMAT_ABBREV_ALL As Int
    • FORMAT_ABBREV_MONTH As Int
    • FORMAT_ABBREV_RELIVE As Int
    • FORMAT_ABBREV_TIME As Int
    • FORMAT_ABBREV_WEEKDAY As Int
    • FORMAT_CAP_AMPM As Int
    • FORMAT_CAP_MIDNIGHT As Int
    • FORMAT_CAP_NOON As Int
    • FORMAT_CAP_NOON_MIDNIGHT As Int
    • FORMAT_NO_MIDNIGHT As Int
    • FORMAT_NO_MONTH_DAY As Int
    • FORMAT_NO_NOON As Int
    • FORMAT_NO_NOON_MIDNIGHT As Int
    • FORMAT_NO_YEAR As Int
    • FORMAT_NUMERIC_DATE As Int
    • FORMAT_SHOW_DATE As Int
    • FORMAT_SHOW_TIME As Int
    • FORMAT_SHOW_WEEKDAY As Int
    • FORMAT_SHOW_YEAR As Int
    • FORMAT_UTC As Int
    • LENGTH_LONG As Int
    • LENGTH_MEDIUM As Int
    • LENGTH_SHORT As Int
    • LENGTH_SHORTER As Int
    • LENGTH_SHORTEST As Int
    Methods:
    • FormatDateRange (StartTicks As Long, EndTicks As Long, Flags As Int) As String
      Formats a date or a time range according to the local conventions.

      Note that this is a convenience method. Using it involves creating an
      internal Formatter instance on-the-fly, which is somewhat costly in terms
      of memory and time.

      StartTicks - start time
      EndTicks - end time
      Flags - a bit mask of options
    • FormatDateTime (Ticks As Long, Flags As Int) As String
      Formats a date or a time according to the local conventions. There are
      lots of options that allow the caller to control, for example, if the
      time is shown, if the day of the week is shown, if the month name is
      abbreviated, if noon is shown instead of 12pm, and so on.

      Ticks - time/date to format
      Flags - a bit mask of options
    • FormatElapsedTime (Seconds As Long) As String
      Formats an elapsed time in the form "MM:SS" or "H:MM:SS" for display on
      the call-in-progress screen.

      Seconds - the elapsed time in seconds.
    • GetRelativeDateTimeString (Ticks As Long, MinResolution As Long, TransitionResolution As Long, Flags As Int) As CharSequence
      Return string describing the elapsed time since startTime formatted like
      "[relative time/date], [time]".

      <b>Ticks</b> - some time in the past.

      <b>MinResolution</b> - the minimum elapsed time (in milliseconds) to
      report when showing relative times. For example, a time 3 seconds in the
      past will be reported as "0 minutes ago" if this is set to
      MINUTE_IN_MILLIS.

      <b>TransitionResolution</b> - the elapsed time (in milliseconds) at which
      to stop reporting relative measurements. Elapsed times greater than this
      resolution will default to normal date formatting. For example, will
      transition from "6 days ago" to "Dec 12" when using WEEK_IN_MILLIS.

      <b>Flags</b> - a bit mask of options
    • GetRelativeTimeSpanString (Ticks As Long, Now As Long, MinResolution As Long, Flags As Int) As CharSequence
      Returns a string describing 'time' as a time relative to 'now'.

      Time spans in the past are formatted like "42 minutes ago". Time spans in
      the future are formatted like "in 42 minutes". Can use
      FORMAT_ABBREV_RELATIVE flag to use abbreviated relative times, like
      "42 mins ago".

      <b>Ticks</b> - the time to describe, in milliseconds

      <b>Now</b> - the current time in
      milliseconds

      <b>MinResolution</b> - the minimum timespan to report. For example,
      a time 3 seconds in the past will be reported as "0 minutes ago" if this
      is set to MINUTE_IN_MILLIS. Pass one of 0, MINUTE_IN_MILLIS,
      HOUR_IN_MILLIS, DAY_IN_MILLIS, WEEK_IN_MILLIS

      <b>Flags</b> - a bit mask of
      formatting options, such as FORMAT_NUMERIC_DATE or FORMAT_ABBREV_RELATIVE
    • IsToday (Ticks As Long) As Boolean
      Returns true if the supplied Ticks value is today else false
  • AHLocale
    Methods:
    • Initialize
      Initializes the AHLocale object with the default locale.
    • Initialize2 (language As String)
      Initializes the AHLocale object using the specified language.
    • Initialize3 (language As String, country As String)
      Initializes the AHLocale object using the specified language and country.
    • InitializeUS
      Initializes the AHLocale Object with <strong>en_US</strong> locale. This locale is
      available on every device.
    Properties:
    • AmPmStrings() As String [read only]
      Returns the array of strings which represent AM and PM.
    • AvailableLocales As List [read only]
      Returns the system's installed locales. These are returned as a B4A List of AHLocale Objects.
      There are only locales in this list which have a non empty country and language.
    • Country As String [read only]
      Returns the country/region code for this locale, which will either be the
      empty string or an uppercase ISO 3166 2-letter code.
    • CurrencyCode As String [read only]
      Returns this currency's ISO 4217 currency code.
    • CurrencyFractionDigits As Int [read only]
      Returns the default number of fraction digits for this currency.
    • CurrencySymbol As String [read only]
      Returns the localized currency symbol for this currency in locale.
    • DisplayCountry As String [read only]
      Returns the name of this locale's country, localized to locale. Returns
      the empty string if this locale does not correspond to a specific country
    • DisplayLanguage As String [read only]
      Returns the name of this locale's language, localized to locale. If the
      language name is unknown, the language code is returned.
    • DisplayName As String [read only]
      Returns this locale's language name, country name, and variant, localized
      to locale. The exact output form depends on whether this locale
      corresponds to a specific language, country and variant, such as:
      English, English (United States), English (United States,Computer),
      anglais (?tats-Unis), anglais (?tats-Unis,informatique).
    • EnglishCountry As String [read only]
      Returns the name of this locale's country in english. Returns
      the empty string if this locale does not correspond to a specific country
    • EnglishLanguage As String [read only]
      Returns the name of this locale's language in english. If the
      language name is unknown, the language code is returned.
    • EnglishName As String [read only]
      Returns this locale's language name, country name, and variant in english.
      The exact output form depends on whether this locale
      corresponds to a specific language, country and variant, such as:
      English, English (United States), English (United States,Computer),
      anglais (?tats-Unis), anglais (?tats-Unis,informatique).
    • FirstDayOfWeek As Int [read only]
      Gets the first day of the week
    • ISO3Country As String [read only]
      Gets the three letter ISO country code which corresponds to the country
      code for this Locale.
    • ISO3Language As String [read only]
      Gets the three letter ISO language code which corresponds to the language
      code for this Locale.
    • ISOCode As String [read only]
      Returns the ISO Code for this Locale such as <strong>en_US</strong> or <strong>de_DE</strong>
    • ISOCountries() As String [read only]
      Gets the list of two letter ISO country codes which can be used as the
      country code for a Locale.
    • ISOLanguages() As String [read only]
      Gets the list of two letter ISO language codes which can be used as the
      language code for a Locale.
    • Initialized As Boolean [read only]
      Returns if the object is initialized
    • Language As String [read only]
      Gets the language code for this Locale or the empty string if no language
      was set.
    • Months() As String [read only]
      Returns the array of strings containing the full names of the months.
    • ShortMonths() As String [read only]
      Returns the array of strings containing the abbreviated names of the months.
    • ShortWeekDays() As String [read only]
      Returns the array of strings containing the abbreviated names of the days of the week.
    • WeekDays() As String [read only]
      Returns the array of strings containing the full names of the days of the week.
  • AHNumeric
    Methods:
    • Format (Value As Double) As String
      Format the number to a string using the pattern and rules of this object.
    • Initialize
      Initializes a standard NumberFormat object with the standard locale
    • Initialize2 (Locale As AHLocale)
      Initializes a standard NumberFormat object with the given locale.
    • InitializeCurrency
      Initializes a currency NumberFormat object with the standard locale
    • InitializeCurrency2 (Locale As AHLocale)
      Initializes a currency NumberFormat object with the given locale.
    • InitializeInteger
      Initializes an integer NumberFormat object with the standard locale
    • InitializeInteger2 (Locale As AHLocale)
      Initializes an integer NumberFormat object with the given locale.
    • InitializeNumber
      Initializes a standard NumberFormat object with the standard locale
    • InitializeNumber2 (Locale As AHLocale)
      Initializes a standard NumberFormat object with the given locale.
    • InitializePercent
      Initializes a percent NumberFormat object with the standard locale
    • InitializePercent2 (Locale As AHLocale)
      Initializes a percent NumberFormat object with the given locale.
    • Parse (Value As String) As Number
      Parse the given string and convert it to a number. This may throw a
      ParseException if the format of the string is not correct.
    Properties:
    • MaximumFractionDigits As Int
      Set or get the maximum fraction digits.
    • MaximumIntegerDigits As Int
      Set or get the maximum integer digits.
    • MinimumFractionDigits As Int
      Set or get the minimum fraction digits.
    • MinimumIntegerDigits As Int
      Set or get the minimum integer digits
    • Pattern As String
      Set or get the pattern that is used for formatting and parsing.
  • AHTimeZone
    Fields:
    • STYLE_LONG As Int
    • STYLE_SHORT As Int
    Methods:
    • GetDisplayName (DaylightTime As Boolean, Style As Int) As String
      Returns the Display name of this timezone

      DaylightTime - Set to true if you want to have DST included into the name
      Style - AHTimeZone.SHORT or AHTimeZone.LONG format
    • GetDisplayName2 (DaylightTime As Boolean, Style As Int, Locale As AHLocale) As String
      Returns the Display name of this timezone

      DaylightTime - Set to true if you want to have DST included into the name
      Style - AHTimeZone.SHORT or AHTimeZone.LONG format
      Locale - a AHLocale object to set in which language you want the displayname
    • GetOffset (Date As Long) As Long
      Returns the offset in milliseconds from UTC for this time zone at time.
      The offset includes daylight savings time if the specified date is within the daylight savings time period.

      Date - Date for which you want to have the info
    • InDaylightTime (Date As Long) As Boolean
      Returns true if Date is in a daylight savings time period for this time zone.

      Date - Date for which you want to get the info
    • Initialize
      Initialize a AHTimeZone object with default timezone
    • Initialize2 (ID As String)
      Initializes a AHTimeZone object with the given TimeZone ID

      ID - TimeZone ID like "Europe/Berlin"
    Properties:
    • AvailableIds As List [read only]
      Returns a list of available timezone IDs on this device.
      One of the results can be passed to the Initialize2() Method to reinitialize
      an AHTimeZone object with a different timezone
    • DSTSavings As Long [read only]
      Returns the daylight savings offset in milliseconds for this time zone.
      The base implementation returns 3600000 (1 hour) for time zones that use daylight savings
      time and 0 for timezones that do not.
      Note that this method doesn't tell you whether or not to apply the offset: you need to call
      InDaylightTime() for the specific time you're interested in. If this method returns a non-zero
      offset, that only tells you that this TimeZone sometimes observes daylight savings.
    • ID As String
      Gets or sets the timezone ID as String for this timezone
    • RawOffset As Long
      Sets or gets the Raw offset for this timezone
  • AHTranslator
    Methods:
    • GetText (text As String) As String
      Searches for the text in the translation table. If a translation is
      available it will be returned. If no translation is available the text is
      added to the missing translation table and the original text is returned.
      So you can write your whole program in a default language. If a
      translation is available it will be used, if not, the text will be
      returned in the default language.
    • GetText2 (text As String, params As List) As String
      Searches for the text in the translation table and returns the translated
      text.

      You can use Placeholders in the form of {1} {2} etc. which will be
      replaced with the content of the second parameter. {1} will be replaced
      with the first item in the Array/List, {2} with the second one and so on.
    • Initialize (dir As String, basename As String)
      Initializes a translation object with the device language. Tries to read a
      translation file with the following name convention: basename_language.lng
    • Initialize2 (dir As String, basename As String, language As String)
      Initializes a translation object with the given language. Tries to read a
      translation file with the following name convention: basename_language.lng
    • Initialize3 (dir As String, basename As String, language As String, country As String)
      Initializes a translation object with the given language and country code.
      Tries to read a translation file with the following name
      convention: basename_language_country.lng
    • WriteTranslation (dir As String, filename As String)
      Writes two files to the specified dir. The current translation Map is
      written to [filename]_[language].lng and the missing translation Map is
      written to [filename]_miss_[language].lng
    Properties:
    • CurrentCountry As String [read only]
      Returns the current County code
    • CurrentFile As String [read only]
      Returns current file name of language file
    • CurrentLanguage As String [read only]
      Returns current Language code
    • DefaultLanguage As String
      Sets or gets the default language. This is the language used when no language file is found.
      If you don't set it the default language will be empty and is not used.
    • Extension As String
      Sets or gets the current file extension
    • MissingTranslationMap As Map [read only]
      Returns a Map object with all text phrases which are missing in the
      translation file.
    • TranslationMap As Map
      Returns a Map object with the current translations

History:
V1.1:
  • fixed Documentation
  • fixed some bugs (DisplayXXX methods)
  • new AHDateTime object
  • some minor improvements

V1.11:
  • fixed problem with AvailableLocales not working on all devices

V1.12:
  • new AHTimeZone object to get information from timezones

V1.13: (never released)
  • Add TimeZone property to AHDateTime object

V1.14:
  • AHTranslator.java - Removed log output
  • Timezone.java - fixed type

V1.15:
  • AHDateUtils object - new
  • AHNumeric object - new
V1.16:
  • AHDateTime - Methods for getting default date and time format strings
  • AHTranslation - Support for Countries
  • AHTranslation - Support for default language
  • AHTranslation - Support for different file extensions
 

Attachments

  • LocaleExample.zip
    8.3 KB · Views: 3,794
  • TimeZoneExample.zip
    5.7 KB · Views: 1,933
  • DateUtilsExample.zip
    6.1 KB · Views: 1,907
  • AHLocale1_16.zip
    17.3 KB · Views: 3,916
Last edited:

agraham

Expert
Licensed User
Longtime User
Shows 1.10 for me. Have you either quit and restarted the IDE since adding the latest library or done a right-click -> Refresh on the Libs tab?

Alternatively have you added the latest library and xml to the Basic4android Libraries folder but still have the old version in your Additional libraries folder?
 

bluedude

Well-Known Member
Licensed User
Longtime User
AHLocal

agraham,

restarted multiple times, have done refresh multiple times and have no additional libraries folder. All is in my Libraries folder.

Have an old version in a complete other directory (have multiple B4A versions) so that isn't the problem.

So it is a weird problem.
 

bluedude

Well-Known Member
Licensed User
Longtime User
Old version

Don't know why but removed the libraries from my very old B4A version and now it shows up in v 1.10 in my new B4A. Very weird.
 

Cableguy

Expert
Licensed User
Longtime User
I need help from you GURUs....

How do I set a multi line text?

Something like:

Text = This is the Text
This is a second line

P.S: I am using 'Text = Texto' for the translations and is working fine even with multi word frases.
 

corwin42

Expert
Licensed User
Longtime User
How do I set a multi line text?

Something like:

Text = This is the Text
This is a second line

Try using

Text = This is the Text\nThis is a second line
 

Cableguy

Expert
Licensed User
Longtime User
I already did,

This is the text\ this is a second line of text gives me a single concatenated line!
This is the text\nthis is a second line of text gives me only the fisrt sentence up to the \

PS: Its works with your suggestion, I had an extra (?) crlf seperating the two text lines, so I think I cannot do:

This is 1 line\n
this is 2 line\n
This is 3 line

??
 
Last edited:

Cableguy

Expert
Licensed User
Longtime User
Ok, so now I found a way to keep it clean.

I can use this scheme:

This is line 1\
\n This is line 2\
\n This is line 3
 

jo1234

Active Member
Licensed User
Longtime User
Hi Markus,

thanks for the great lib. That helps a lot. :sign0098:

However, as I understand it, only strings that have been used are stored in the missing translation list.

But what about strings that have not been used (like error messages)?
Moreover, I have to implement a call to WriteTranslation, each time I want to get the list of missing translations.


I think it would be great to have separate program, which scans the .b4a and .bas files for "GetText" and creates for each of them a .properties file with all strings following a "GetText".
This way, you could easily update your translations and be sure that you caught all strings that need to be translated.

Is that something you could consider writing?

thanks again for the great lib,
Johannes

BTW: What resource editor do you recommend to do the translations?
I tried the 'DOKSoft Properties Editor', which is ok.
 

corwin42

Expert
Licensed User
Longtime User
However, as I understand it, only strings that have been used are stored in the missing translation list.

But what about strings that have not been used (like error messages)?
Moreover, I have to implement a call to WriteTranslation, each time I want to get the list of missing translations.

Yes, the missing translations are checked and gererated if you call one of the GetText() functions. This whole mechanism and the WriteTranslation functions are intended for helping the developer to create the properties files.
I know that this is not perfect this way but it's better than nothing.

I think it would be great to have separate program, which scans the .b4a and .bas files for "GetText" and creates for each of them a .properties file with all strings following a "GetText".
This way, you could easily update your translations and be sure that you caught all strings that need to be translated.

Is that something you could consider writing?

This is a nice idea but unfortunately I don't have the time to write such a program.

I can't make any suggestions for a properties editor because I currently don't use one but if you find a good free one, feel free to post it here.
 

COBRASoft

Active Member
Licensed User
Longtime User
Sorry it took so long, here are the logs... I hope this will help.

** Activity (main) Create, isFirst = true **
GC_CONCURRENT freed 1458K, 57% free 2962K/6791K, external 2091K/2133K, paused 4ms+2ms

FileName:LocaleExample_en.lng

Pattern: yyyy-MM-dd HH:mm:ss

2012-01-28 18:46:07
05/19/2011

00:45:00
GC_CONCURRENT freed 361K, 51% free 3350K/6791K, external 2091K/2133K, paused 1ms+2ms

Error getting ICU gregorian resource bundle: U_MISSING_RESOURCE_ERROR

Shutting down VM
threadid=1: thread exiting with uncaught exception (group=0x2aac8578)

FATAL EXCEPTION: main
java.lang.AssertionError: couldn't initialize LocaleData for locale th_TH_TRADITIONAL
at com.ibm.icu4jni.util.LocaleData.initLocaleData(LocaleData.java:322)
at com.ibm.icu4jni.util.LocaleData.makeLocaleData(LocaleData.java:128)
at com.ibm.icu4jni.util.LocaleData.get(LocaleData.java:103)
at java.util.Calendar.<init>(Calendar.java:724)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:338)
at java.util.GregorianCalendar.<init>(GregorianCalendar.java:314)
at de.amberhome.AHLocale.init(AHLocale.java:36)
at de.amberhome.AHLocale.getAvailableLocales(AHLocale.java:81)
at de.amberhome.localeexample.main._activity_create(main.java:279)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at anywheresoftware.b4a.BA.raiseEvent2(BA.java:113)
at de.amberhome.localeexample.main.afterFirstLayout(main.java:84)
at de.amberhome.localeexample.main.access$100(main.java:16)
at de.amberhome.localeexample.main$WaitForLayout.run(main.java:72)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3701)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
at dalvik.system.NativeStart.main(Native Method)
Force finishing activity de.amberhome.localeexample/.main
Activity pause timeout for HistoryRecord{2aff1790 de.amberhome.localeexample/.main}
 

RiverRaid

Active Member
Licensed User
Longtime User
\n?

Hi!

First of all: Thanks for your great library!!!!!

I use:
B4X:
InfolblErstelltVon.Text = trans.GetText2("{1}{2}\n crlf Version {3}\n\nCopyright © 2012 me",Array As String(PhonePackageManager.GetApplicationLabel("com.com.com"),tmpDonateText,PhonePackageManager.GetVersionName("com.com.com")))
but the library is not interpreting the "\n" as new line...
Am I doing something wrong, or do i have to find an other way?

Thanks!
 

corwin42

Expert
Licensed User
Longtime User
I think you will have to use something like

B4X:
trans.GetText2("{1}{2}" & CRLF & "Version {3}" & CRLF & CRLF "Copyright � 2012 me",Array As String(PhonePackageManager.GetApplicationLabel("com.com.com"),tmpDonateText,PhonePackageManager.GetVersionName("com.com.com")))
 

sigster

Active Member
Licensed User
Longtime User
Hi

I try your Sample I have Icelandic Language in my mobile
it don't show up in spinner

Regards
Sigster
 
Top