diff --git a/en/application-dev/internationalization/Readme-EN.md b/en/application-dev/internationalization/Readme-EN.md index d7042968cf5c6824e49f77911e207e4cbb4be443..6c89740e15daf19fcb712aba339484caad2ed7c3 100644 --- a/en/application-dev/internationalization/Readme-EN.md +++ b/en/application-dev/internationalization/Readme-EN.md @@ -1,6 +1,6 @@ # Internationalization - [Internationalization Overview](international-overview.md) -- [Internationalization Development (intl)](intl-guidelines.md) -- [Internationalization Development (i18n)](i18n-guidelines.md) +- [intl Development](intl-guidelines.md) +- [i18n Development](i18n-guidelines.md) diff --git a/en/application-dev/internationalization/i18n-guidelines.md b/en/application-dev/internationalization/i18n-guidelines.md index 62bf66fd7cabb7e30c765126ddacba639bd951f5..8218f2561376c4119f66be0175c5c9ea16c7d024 100644 --- a/en/application-dev/internationalization/i18n-guidelines.md +++ b/en/application-dev/internationalization/i18n-guidelines.md @@ -1,391 +1,732 @@ -# Internationalization Development (I18N) +# i18n Development -This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For more details about APIs and their usage, see [I18N](../reference/apis/js-apis-i18n.md). +The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. For more details about APIs and their usage, see [i18n](../reference/apis/js-apis-i18n.md). -## Obtaining System Language and Region Information +The [intl](intl-guidelines.md) module provides basic i18n capabilities through the standard i18n interfaces defined in ECMA 402. It works with the **i18n** module to provide a complete suite of i18n capabilities. -You can use APIs provided in the following table to obtain the system language and region information. +## Obtaining and Setting i18n Information +The system provides APIs to configure information such as the system language, preferred language, country or region, 24-hour clock, and local digit switch. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | -| ohos.i18n | getSystemRegion(): string | Obtains the system region. | -| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | -| ohos.i18n | isRTL(locale: string): boolean7+ | Checks whether the locale uses a right-to-left (RTL) language. | -| ohos.i18n | is24HourClock(): boolean7+ | Checks whether the system uses a 24-hour clock. | -| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | -| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | - +| Class | API | Description | +| --------- | ---------------------------------------- | --------------------- | +| System | getDisplayCountry(country:string,locale:string,sentenceCase?:boolean):string9+ | Obtains the localized representation of a country. | +| System | getDisplayLanguage(language:string,locale:string,sentenceCase?:boolean):string9+ | Obtains the localized representation of a language. | +| System | getSystemLanguages():Array9+ | Obtains the system language list. | +| System | getSystemCountries(language: string):Array9+ | Obtains the list of countries and regions supported for the specified language. | +| System | isSuggested(language: string, region?: string): boolean9+ | Checks whether the system language matches the specified region. | +| System | getSystemLanguage():string9+ | Obtains the system language. | +| System | setSystemLanguage(language: string)9+ | Sets the system language. | +| System | getSystemRegion():string9+ | Obtains the system region. | +| System | setSystemRegion(region: string)9+ | Sets the system region. | +| System | getSystemLocale():string9+ | Obtains the system locale. | +| System | setSystemLocale(locale: string)9+ | Sets the system locale. | +| System | is24HourClock():boolean9+ | Checks whether the 24-hour clock is used. | +| System | set24HourClock():boolean9+ | Sets the 24-hour clock. | +| System | addPreferredLanguage(language: string, index?: number)9+ | Adds a preferred language to the specified position on the preferred language list. | +| System | removePreferredLanguage(index: number)9+ | Deletes a preferred language from the specified position on the preferred language list. | +| System | getPreferredLanguageList()9+ | Obtains the preferred language list. | +| System | getFirstPreferredLanguage()9+ | Obtains the first language in the preferred language list. | +| System | getAppPreferredLanguage()9+ | Obtains the preferred language of an application. | +| System | setUsingLocalDigit(flag: boolean)9+ | Sets whether to enable the local digit switch. | +| System | getUsingLocalDigit()9+ | Checks whether the local digit switch is turned on. | +| | isRTL(locale:string):boolean9+ | Checks whether the locale uses a right-to-left (RTL) language.| ### How to Develop +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` + +2. Obtain and set the system language. + + Call **setSystemLanguage** to set the system language. (This is a system API and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) + Call the **getSystemLanguage** API to obtain the system language. + + ```js + try { + I18n.System.setSystemLanguage("en"); // Set the system language to en. + let language = I18n.System.getSystemLanguage(); // language = "en" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } + ``` -1. Obtain the system language. +3. Obtain and set the system locale. + + Call **setSystemRegion** to set the system country or region. (This is a system API and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) + Call **getSystemRegion** to obtain the system country or region. + + ```js + try { + I18n.System.setSystemRegion("CN"); // Set the system country to CN. + let region = I18n.System.getSystemRegion(); // region = "CN" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } + ``` - Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). +4. Obtain and set the system locale. + Call **setSystemLocale** to set the system locale. (This is a system API and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) For details about how to set a locale, see [Setting Locale Information](../internationalization/intl-guidelines.md#setting-locale-information). + Call **getSystemLocale** to obtain the system locale. - ```js - var language = i18n.getSystemLanguage(); + ```js + try { + I18n.System.setSystemLocale("zh-Hans-CN"); // Set the system locale to zh-Hans-CN. + let locale = I18n.System.getSystemLocale(); // locale = "zh-Hans-CN" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -2. Obtain the system region. +5. Check whether the locale uses a right-to-left (RTL) language. + + Call **isRTL** to check whether the locale uses an RTL language. - Call the **getSystemRegion** method to obtain the system region. - - ```js - var region = i18n.getSystemRegion(); + ```js + try { + let rtl = I18n.isRTL("zh-CN"); // rtl = false + rtl = I18n.isRTL("ar"); // rtl = true + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -3. Obtain the system locale. +6. Obtain and set the 24-hour clock. - Call the **getSystemLocale** method to obtain the system locale. - - ```js - var locale = i18n.getSystemLocale(); + Call **set24HourClock** to enable the 24-hour clock. + Call **is24HourClock** to check whether the 24-hour clock is enabled. + + ```js + try { + I18n.System.set24HourClock(true); + let hourClock = I18n.System.is24HourClock(); // hourClock = true + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -4. Check whether the locale's language is RTL. +7. Obtain the localized representation of a language. + + Call **getDisplayLanguage** to obtain the localized representation of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - Call the **isRTL** method to check whether the locale's language is RTL. + ```js + try { + let language = "en"; + let locale = "zh-CN"; + let sentenceCase = false; + let localizedLanguage = I18n.System.getDisplayLanguage(language, locale, sentenceCase); // localizedLanguage = "English" + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } + ``` +8. Obtain the localized representation of a country. - ```js - var rtl = i18n.isRTL("zh-CN"); + Call **getDisplayCountry** to obtain the localized representation of a country. **country** indicates the country to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. + + ```js + try { + let country = "US"; + let locale = "zh-CN"; + let sentenceCase = false; + let localizedCountry = I18n.System.getDisplayCountry(country, locale, sentenceCase); // localizedCountry = "U.S." + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -5. Check whether the system uses a 24-hour clock. +9. Obtain the list of system languages and the list of countries supported by a system language. - Call the **is24HourClock** method to check whether the system uses a 24-hour clock. - - ```js - var hourClock = i18n.is24HourClock(); + Call **getSystemLanguages** to obtain the list of system languages. + Call **getSystemCountries** to obtain the list of countries and regions supported by a system language. + ```js + + try { + let languageList = I18n.System.getSystemLanguages(); // languageList = ["en-Latn-US", "zh-Hans"] + let countryList = I18n.System.getSystemCountries("zh"); // countryList = ["ZW", "YT", ..., "CN", "DE"], 240 countries and regions in total + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -6. Obtain the localized display of a language. +10. Check whether the language matches a country or region. - Call the **getDisplayLanguage** method to obtain the localized display of a language. **language** indicates the language to be localized, **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - - ```js - var language = "en"; - var locale = "zh-CN"; - var sentenceCase = false; - var localizedLanguage = i18n.getDisplayLanguage(language, locale, sentenceCase); + Call **isSuggested** to check whether the language matches a country or region. + + ```js + try { + let isSuggest = I18n.System.isSuggested("zh", "CN"); // isSuggest = true + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` -7. Obtain the localized display of a country. +11. Obtain and set the preferred language. - Call the **getDisplayCountry** method to obtain the localized display of a country name. **country** indicates the country code (a two-letter code in compliance with ISO-3166, for example, CN), **locale** indicates the locale, and **sentenceCase** indicates whether the first letter of the result must be capitalized. - - ```js - var country = "US"; - var locale = "zh-CN"; - var sentenceCase = false; - var localizedCountry = i18n.getDisplayCountry(country, locale, sentenceCase); + Call **addPreferredLanguage** to add a preferred language to the preferred language list. + Call **removePreferredLanguage** to remove a preferred language from the preferred language list. (**addPreferredLanguage** and **removePreferredLanguage** are system APIs and can be called only by system applications with the **UPDATE_CONFIGURATION** permission.) + Call **getPreferredLanguageList** to obtain the preferred language list. + Call **getFirstPreferredLanguage** to obtain the first preferred language in the preferred language list. + Call **getAppPreferredLanguageList** to obtain the preferred language of the application. It is the first language that matches the application resource in the preferred language list. + + ```js + try { + I18n.System.addPreferredLanguage("en-GB", 0); // Set the first language in the preferred language list to en-GB. + let list = I18n.System.getPreferredLanguageList(); // Obtain the preferred language list. Example: list = ["en-GB", ...] + I18n.System.removePreferredLanguage(list.length - 1); // Remove the last preferred language from the preferred language list. + let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // firstPreferredLanguage = "en-GB" + let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Set the preferred language of the application to en-GB if the application contains en-GB resources. + } catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) + } ``` +12. Obtain and set the local digit switch. -## Obtaining Calendar Information + Call **setUsingLocalDigit** to enable the local digit switch. (This is a system API and can be called only by system applications with the UPDATE_CONFIGURATION permission.) + Call **getUsingLocalDigit** to check whether the local digit switch is enabled. + Currently, the local digit switch applies only to the following languages: "ar", "as", "bn", "fa", "mr", "my", "ne", and "ur". -[Calendar](../reference/apis/js-apis-i18n.md#calendar8) APIs are used to obtain calendar information, for example, the localized display of the calendar, the first day of a week, and the minimum count of days in the first week of a year. +```js +try { + I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. + let status = I18n.System.getUsingLocalDigit(); // status = true +} catch(error) { + console.error(`call i18n.System interface failed, error code: ${error.code}, message: ${error.message}`) +} +``` +## Obtain the calendar information. -### Available APIs +[Calendar](../reference/apis/js-apis-i18n.md#calendar8) provides APIs to obtain calendar information, for example, localized representation of the calendar, the start day of a week, and the minimum number of days in the first week of a year. -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getCalendar(locale: string, type?: string): Calendar8+ | Obtains the **Calendar** object for a specific locale and type. | -| ohos.i18n | setTime(date: Date): void8+ | Sets the date for the **Calendar** object. | -| ohos.i18n | setTime(time: number): void8+ | Sets the time for the **Calendar** object. | -| ohos.i18n | set(year: number, month: number, date: number, hour?: number, minute?: number, second?: number): void8+ | Sets the year, month, day, hour, minute, and second for the **Calendar** object. | -| ohos.i18n | setTimeZone(timezone: string): void8+ | Sets the time zone for the **Calendar** object. | -| ohos.i18n | getTimeZone(): string8+ | Obtains the time zone for the **Calendar** object. | -| ohos.i18n | getFirstDayOfWeek(): number8+ | Obtains the first day of a week for the **Calendar** object. | -| ohos.i18n | setFirstDayOfWeek(value: number): void8+ | Sets the first day of a week for the **Calendar** object. | -| ohos.i18n | getMinimalDaysInFirstWeek(): number8+ | Obtains the minimum count of days in the first week of a year. | -| ohos.i18n | setMinimalDaysInFirstWeek(value: number): void8+ | Sets the minimum count of days in the first week of a year. | -| ohos.i18n | getDisplayName(locale: string): string8+ | Obtains the localized display of the **Calendar** object. | -| ohos.i18n | isWeekend(date?: Date): boolean8+ | Checks whether a given date is a weekend. | +### Available APIs +| Class | API | Description | +| --------- | ---------------------------------------- | --------------------- | +| | getCalendar(locale:string,type?:string):Calendar8+ | Obtains the **Calendar** object for a specific locale and type.| +| Calendar | setTime(date:Date): void8+ | Sets the date for this **Calendar** object. | +| Calendar | setTime(time:number): void8+ | Sets the date for this **Calendar** object. | +| Calendar | set(year:number,month:number,date:number,hour?:number,minute?:number,second?:number): void8+ | Sets the year, month, day, hour, minute, and second for this **Calendar** object. | +| Calendar | setTimeZone(timezone:string): void8+ | Sets the time zone of this **Calendar** object. | +| Calendar | getTimeZone():string8+ | Obtains the time zone of this **Calendar** object. | +| Calendar | getFirstDayOfWeek():number8+ | Obtains the start day of a week for this **Calendar** object. | +| Calendar | setFirstDayOfWeek(value:number): void8+ | Sets the first day of a week for the **Calendar** object. | +| Calendar | getMinimalDaysInFirstWeek():number8+ | Obtains the minimum number of days in the first week of a year. | +| Calendar | setMinimalDaysInFirstWeek(value:number): void8+ | Sets the minimum number of days in the first week of a year. | +| Calendar | getDisplayName(locale:string):string8+ | Obtains the localized display of the **Calendar** object. | +| Calendar | isWeekend(date?:Date):boolean8+ | Checks whether the specified date in this **Calendar** object is a weekend. | ### How to Develop -1. Instantiate a **Calendar** object. +1. Import the **i18n** module. - Call the **getCalendar** method to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. + ```js + import I18n from '@ohos.i18n' + ``` + +2. Instantiate a **Calendar** object. + Call **getCalendar** to obtain the time zone object of a specific locale and type (**i18n** is the name of the imported module). **type** indicates the valid calendar type, for example, **buddhist**, **chinese**, **coptic**, **ethiopic**, **hebrew**, **gregory**, **indian**, **islamic_civil**, **islamic_tbla**, **islamic_umalqura**, **japanese**, and **persian**. If **type** is left unspecified, the default calendar type of the locale is used. - ```js - var calendar = i18n.getCalendar("zh-CN", "gregory"); + ```js + let calendar = I18n.getCalendar("zh-CN", "chinese"); // Create the Calendar object for the Chinese lunar calendar. ``` -2. Set the time for the **Calendar** object. +3. Set the time for the **Calendar** object. + + Call **setTime** to set the time of the **Calendar** object. Two types of parameters are supported. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT. - Call the **setTime** method to set the time of the **Calendar** object. This method receives two types of parameters. One is a **Date** object, and the other is a value indicating the number of milliseconds elapsed since January 1, 1970, 00:00:00 GMT. - - ```js - var date1 = new Date(); + ```js + let date1 = new Date(); calendar.setTime(date1); - var date2 = 1000; + let date2 = 1000; calendar.setTime(date2); ``` -3. Set the year, month, day, hour, minute, and second for the **Calendar** object. +4. Set the year, month, day, hour, minute, and second for this **Calendar** object. - Call the **set** method to set the year, month, day, hour, minute, and second for the **Calendar** object. - - ```js + Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object. + + ```js calendar.set(2021, 12, 21, 6, 0, 0) ``` -4. Set and obtain the time zone for the **Calendar** object. - - Call the **setTimeZone** and **getTimeZone** methods to set and obtain the time zone for the **Calendar** object. The **setTimeZone** method requires an input string to indicate the time zone to be set. +5. Set and obtain the time zone for the **Calendar** object. + Call **setTimeZone** and **getTimeZone** to set and obtain the time zone of the **Calendar** object. Note that **setTimeZone** requires an input string to indicate the time zone to be set. - ```js + ```js calendar.setTimeZone("Asia/Shanghai"); - var timezone = calendar.getTimeZone(); + let timezone = calendar.getTimeZone(); // timezone = "China Standard Time" ``` -5. Set and obtain the first day of a week for the **Calendar** object. +6. Set and obtain the first day of a week for the **Calendar** object. - Call the **setFirstDayOfWeek** and **getFirstDayOfWeek** methods to set and obtain the first day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday. + Call **setFirstDayOfWeek** and **getFirstDayOfWeek** to set and obtain the start day of a week for the **Calendar** object. **setFirstDayOfWeek** must be set to a value indicating the first day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday. - - ```js + ```js calendar.setFirstDayOfWeek(1); - var firstDayOfWeek = calendar.getFirstDayOfWeek(); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 ``` -6. Set and obtain the minimum count of days in the first week for the **Calendar** object. +7. Set and obtain the minimum count of days in the first week for the **Calendar** object. + Call **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** to set and obtain the minimum number of days in the first week for the **Calendar** object. - Call the **setMinimalDaysInFirstWeek** and **getMinimalDaysInFirstWeek** methods to set and obtain the minimum count of days in the first week for the **Calendar** object. - - ```js + ```js calendar.setMinimalDaysInFirstWeek(3); - var minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 ``` -7. Obtain the localized display of the **Calendar** object. +8. Obtain the localized representation of the **Calendar** object. + Call **getDisplayName** to obtain the localized representation of the **Calendar** object. + + ```js + let localizedName = calendar.getDisplayName("zh-CN"); // localizedName = " Lunar Calendar" + ``` - Call the **getDisplayName** method to obtain the localized display of the **Calendar** object. +9. Check whether a date is a weekend. + Call **isWeekend** to determine whether the input date is a weekend. - ```js - var localizedName = calendar.getDisplayName("zh-CN"); + ```js + let date = new Date(2022, 12, 12, 12, 12, 12); + let weekend = calendar.isWeekend(date); // weekend = false ``` -8. Check whether a date is a weekend. +## Formatting a Phone Number + +[PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8) provides APIs to format phone numbers of different countries or regions and check whether the phone number format is correct. - Call the **isWeekend** method to determine whether the input date is a weekend. +### Available APIs - - ```js - var date = new Date(); - var weekend = calendar.isWeekend(date); +| Class | API | Description | +| --------- | ---------------------------------------- | ----------------------- | +| PhoneNumberFormat | constructor(country:string,options?:PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object.| +| PhoneNumberFormat | isValidNumber(number:string):boolean8+ | Checks whether the value of **number** is a phone number in the correct format.| +| PhoneNumberFormat | format(number:string):string8+ | Formats the value of **number** based on the specified country and style. | +| PhoneNumberFormat | getLocationName(number: string, locale: string): string9+ | Obtains the home location of a phone number. | + +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' ``` +2. Instantiate a **PhoneNumberFormat** object. -## Formatting a Phone Number + Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. -[PhoneNumberFormat](../reference/apis/js-apis-i18n.md#phonenumberformat8) APIs are used to format phone numbers in different countries and check whether the phone number formats are correct. + ```js + let phoneNumberFormat = new I18n.PhoneNumberFormat("CN", {type: "E164"}); + ``` +3. Check whether the phone number format is correct. + + Call **isValidNumber** to check whether the format of the input phone number is correct. + + ```js + let validNumber = phoneNumberFormat.isValidNumber("15812341234"); // validNumber = true + ``` + +4. Format a phone number. + + Call **format** to format the input phone number. + + ```js + let formattedNumber = phoneNumberFormat.format("15812341234"); // formattedNumber = "+8615812341234" + ``` + +## Measurement Conversion + +The **I18NUtil** class provides an API to implement measurement conversion. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)8+ | Instantiates a **PhoneNumberFormat** object. | -| ohos.i18n | isValidNumber(number: string): boolean8+ | Checks whether the value of **number** is a phone number in the correct format. | -| ohos.i18n | format(number: string): string8+ | Formats the value of **number** based on the specified country and style. | +| Class | API | Description | +| --------- | ---------------------------------------- | --------------------------------------- | +| I18NUtil | unitConvert(fromUnit:UnitInfo,toUnit:UnitInfo,value:number,locale:string,style?:string):string9+ | Converts one measurement unit into another and formats the unit based on the specified locale and style.| + +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` + +2. Convert a measurement unit. + + Call [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) to convert a measurement unit and format the display result. + + ```js + let fromUnit = {unit: "cup", measureSystem: "US"}; + let toUnit = {unit: "liter", measureSystem: "SI"}; + let number = 1000; + let locale = "en-US"; + let style = "long"; + let converttedUnit = I18n.I18NUtil.unitConvert(fromUnit, toUnit, number, locale, style); // converttedUnit = "236.588 liters" + ``` + +## Alphabet Indexing + +[IndexUtil](../reference/apis/js-apis-i18n.md#indexutil8) provides APIs to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. + +### Available APIs +| Class | API | Description | +| --------- | ---------------------------------------- | ----------------------- | +| | getInstance(locale?:string):IndexUtil8+ | Instantiates an **IndexUtil** object. | +| IndexUtil | getIndexList():Array<string>8+ | Obtains the index list of the current locale. | +| IndexUtil | addLocale(locale:string): void8+ | Adds the index of a new locale to the index list.| +| IndexUtil | getIndex(text:string):string8+ | Obtains the index of a text object. | ### How to Develop -1. Instantiate a **PhoneNumberFormat** object. +1. Import the **i18n** module. - Call the **PhoneNumberFormat** constructor to instantiate a **PhoneNumberFormat** object. The country code and formatting options of the phone number need to be passed into this constructor. The formatting options are optional, including a style option. Values of this option include: **E164**, **INTERNATIONAL**, **NATIONAL**, and **RFC3966**. + ```js + import I18n from '@ohos.i18n' + ``` + +2. Instantiates an **IndexUtil** object. + Call **getInstance** to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. - ```js - var phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); + + ```js + let indexUtil = I18n.getInstance("zh-CN"); ``` -2. Check whether the phone number format is correct. - Call the **isValidNumber** method to check whether the format of the input phone number is correct. - - ```js - var validNumber = phoneNumberFormat.isValidNumber("15812341234"); +3. Obtain the index list. + + Call **getIndexList** to obtain the alphabet index list of the current locale. + + ```js + let indexList = indexUtil.getIndexList(); // indexList = ["...", "A", "B", "C", ..., "X", "Y", "Z", "..."] ``` -3. Format a phone number. - Call the **format** method of **PhoneNumberFormat** to format the input phone number. - - ```js - var formattedNumber = phoneNumberFormat.format("15812341234"); +4. Add an index. + + Call **addLocale** to add the alphabet index of a new locale to the current index list. + + ```js + indexUtil.addLocale("ar") ``` +5. Obtain the index of a string. -## Measurement Conversion + Call **getIndex** to obtain the alphabet index of a string. -The **unitConvert** API is provided to help you implement measurement conversion. + ```js + let text = "access index"; + let index = indexUtil.getIndex(text); // index = "A" + ``` + +## Obtaining Line Breaks of Text +When a text is displayed in more than one line, use [BreakIterator8](../reference/apis/js-apis-i18n.md#breakiterator8) APIs to obtain the line break positions of the text. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string8+ | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | - +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| | getLineInstance(locale:string):BreakIterator8+ | Instantiates a **BreakIterator** object. | +| BreakIterator | setLineBreakText(text:string): void8+ | Sets the text to be processed. | +| BreakIterator | getLineBreakText():string8+ | Obtains the text to be processed. | +| BreakIterator | current():number8+ | Obtains the current position of a **BreakIterator** object in the text being processed. | +| BreakIterator | first():number8+ | Sets a **BreakIterator** object to the first breakable point. | +| BreakIterator | last():number8+ | Sets a **BreakIterator** object to the last breakable point. | +| BreakIterator | next(index?:number):number8+ | Moves a **BreakIterator** object to the break point according to **index**. | +| BreakIterator | previous():number8+ | Moves a **BreakIterator** object to the previous break point. | +| BreakIterator | following(offset:number):number8+ | Moves a **BreakIterator** object to the break point following the position specified by **offset**.| +| BreakIterator | isBoundary(offset:number):boolean8+ | Determines whether a position is a break point. | ### How to Develop -1. Convert a measurement unit. - Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) method to convert a measurement unit and format the display result. +1. Import the **i18n** module. - - ```js - var fromUnit = {unit: "cup", measureSystem: "US"}; - var toUnit = {unit: "liter", measureSystem: "SI"}; - var number = 1000; - var locale = "en-US"; - var style = "long"; - i18n.Util.unitConvert(fromUtil, toUtil, number, locale, style); - ``` + ```js + import I18n from '@ohos.i18n' + ``` +2. Instantiate a **BreakIterator** object. -## Alphabet Index + Call **getLineInstance** to instantiate a **BreakIterator** object. -[IndexUtil](../reference/apis/js-apis-i18n.md#indexutil8) APIs are used to obtain the alphabet indexes of different locales and calculate the index to which a string belongs. + ```js + let locale = "en-US" + let breakIterator = I18n.getLineInstance(locale); + ``` +3. Set and access the text that requires line breaking. -### Available APIs + Call **setLineBreakText** and **getLineBreakText** to set and access the text that requires line breaking. -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getInstance(locale?: string): IndexUtil8+ | Instantiates an **IndexUtil** object. | -| ohos.i18n | getIndexList(): Array<string>8+ | Obtains the index list of the current locale. | -| ohos.i18n | addLocale(locale: string): void8+ | Adds the index of a new locale to the index list. | -| ohos.i18n | getIndex(text: string): string8+ | Obtains the index of **text**. | + ```js + let text = "Apple is my favorite fruit"; + breakIterator.setLineBreakText(text); + let breakText = breakIterator.getLineBreakText(); // breakText = "Apple is my favorite fruit" + ``` +4. Obtain the current position of the **BreakIterator** object. -### How to Develop + Call **current** to obtain the current position of the **BreakIterator** object in the text being processed. -1. Instantiate an **IndexUtil** object. + ```js + let pos = breakIterator.current(); // pos = 0 + ``` - Call the **getInstance** method to instantiate an **IndexUtil** object for a specific locale. When the **locale** parameter is empty, instantiate an **IndexUtil** object of the default locale. +5. Set the position of a **BreakIterator** object. + The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed. - ```js - var indexUtil = i18n.getInstance("zh-CN"); + ```js + let firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text (firstPos = 0). + let lastPos = breakIterator.last(); // Sets a BreakIterator object to the last break point, that is, the position after the text end (lastPos = 26). + // Move a BreakIterator object forward or backward by a certain number of break points. + // If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward. + // If the object is moved out of the text length range, **-1** is returned. + let nextPos = breakIterator.next(-2); // nextPos = 12 + let previousPos = breakIterator.previous(); // Move a BreakIterator object to the previous break point. When the text length is out of the range, **-1** is returned. Example: previousPos = 9 + // Move a BreakIterator object to the break point following the position specified by **offset**. If the object is moved out of the text length range, **-1** is returned. + let followingPos = breakIterator.following(10); // Example: followingPos = 12 ``` -2. Obtain the index list. +6. Determine whether a position is a break point. - Call the **getIndexList** method to obtain the alphabet index list of the current locale. - - ```js - var indexList = indexUtil.getIndexList(); + Call **isBoundary** to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. + + ```js + let isboundary = breakIterator.isBoundary(5); // isboundary = false ``` -3. Add an index. +## Obtaining the Time Zone - Call the **addLocale** method to add the alphabet index of a new locale to the current index list. - - ```js - indexUtil.addLocale("ar") +[TimeZone](../reference/apis/js-apis-i18n.md#timezone) provides APIs to obtain time zone information, such as the time zone ID, localized representation, and time zone offset. + +### Available APIs + +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| | getTimeZone(zoneID?: string): TimeZone7+ | Obtains a **TimeZone** object. | +| TimeZone | getID(): string7+ | Obtains the time zone ID. | +| TimeZone | getDisplayName(locale?: string, isDST?: boolean): string7+ | Obtains the localized representation of the time zone. | +| TimeZone | getRawOffset(): number7+ | Obtains the offset between the time zone represented by a **TimeZone** object and the UTC time zone. | +| TimeZone | getOffset(date?: number): number7+ | Obtains the offset between the time zone represented by a **TimeZone** object and the UTC time zone at a certain time point. | +| TimeZone | getAvailableIDs(): Array9+ | Obtains the list of time zone IDs supported by the system. | +| TimeZone | getAvailableZoneCityIDs(): Array9+ | Obtains the list of time zone city IDs supported by the system. | +| TimeZone | getCityDisplayName(cityID: string, locale: string): string9+ | Obtains the localized representation of a time zone city in the specified locale. | +| TimeZone | getTimezoneFromCity(cityID: string): TimeZone9+ | Obtains the **TimeZone** object corresponding to the specified time zone ID.| + +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' ``` -4. Obtain the index of a string. +2. Instantiate the **TimeZone** object, and obtain the time zone information. - Call the **getIndex** method to obtain the alphabet index of a string. - - ```js - var text = "access index"; - indexUtil.getIndex(text); + Call **getTimeZone** to obtain the **TimeZone** object. + + ```js + let timezone = I18n.getTimeZone(); // If you use the default settings, you'll obtain the TimeZone object corresponding to the system time zone. ``` + Obtain the time zone ID, localized representation, time zone offset, and time zone offset at a certain time point. + + ```js + let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai" + let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "China Standard Time" + let rawOffset = timezone.getRawOffset(); // rawOffset = 28800000 + let offset = timezone.getOffset(new Date().getTime()); // offset = 28800000 + ``` -## Obtaining Line Breaks of Text +3. Obtain the list of time zone IDs supported by the system. + + Call **getAvailableIDs** to obtain the list of time zone IDs supported by the system. + You can use the time zone ID in the time zone ID list as an input parameter of the **getTimeZone** API to create a **TimeZone** object. + + ```js + let timezoneIDs = I18n.TimeZone.getAvailableIDs(); // timezoneIDs = ["America/Adak", ...], which contains 24 time zone IDs in total + let timezone = I18n.getTimeZone(timezoneIDs[0]); + let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "Hawaii-Aleutian Standard Time" + ``` + +4. Obtain the list of time zone city IDs supported by the system. + + Call **getAvailableZoneCityIDs** to obtain the list of time zone city IDs supported by the system. + Call **getCityDisplayName** to obtain the localized representation of the time zone city ID. + Call **getTimezoneFromCity** to create a **TimeZone** object based on the time zone city ID. -When a text is displayed in more than one line, [BreakIterator8](../reference/apis/js-apis-i18n.md#breakiterator8) APIs are used to obtain the line break positions of the text. + ```js + let zoneCityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); // ["Auckland", "Magadan", ...] + let cityDisplayName = I18n.TimeZone.getCityDisplayName(zoneCityIDs[0], "zh-Hans"); // cityDisplayName = "Auckland (New Zealand)" + let timezone = I18n.TimeZone.getTimezoneFromCity(zoneCityIDs[0]); + let timezoneDisplayName = timezone.getDisplayName(); // timezoneDisplayName = "New Zealand Standard Time" + ``` + +## Obtain the **Transliterator** object. +Call [Transliterator](../reference/apis/js-apis-i18n.md#transliterator9) APIs to create a **Transliterator** object and obtain the transliterated string. ### Available APIs -| Module | API | Description | -| -------- | -------- | -------- | -| ohos.i18n | getLineInstance(locale: string): BreakIterator8+ | Instantiates a **BreakIterator** object. | -| ohos.i18n | setLineBreakText(text: string): void8+ | Sets the text to be processed. | -| ohos.i18n | getLineBreakText(): string8+ | Obtains the text to be processed. | -| ohos.i18n | current(): number8+ | Obtains the current position of a **BreakIterator** object in the text being processed. | -| ohos.i18n | first(): number8+ | Sets a **BreakIterator** object to the first breakable point. | -| ohos.i18n | last(): number8+ | Sets a **BreakIterator** object to the last breakable point. | -| ohos.i18n | next(index?: number): number8+ | Moves a **BreakIterator** object to the break point according to **index**. | -| ohos.i18n | previous(): number8+ | Moves a **BreakIterator** object to the previous break point. | -| ohos.i18n | following(offset: number): number8+ | Moves a **BreakIterator** object to the break point following the position specified by **offset**. | -| ohos.i18n | isBoundary(offset: number): boolean8+ | Determines whether a position is a break point. | +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| Transliterator | getAvailableIDs():Array9+ | Obtains the transliterator ID list. | +| Transliterator | getInstance(): Transliterator9+ | Creates a **Transliterator** object. | +| Transliterator | transform(text: string): string9+ | Obtains a transliterated string. | +### How to Develop + +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` + +2. Obtains the transliterator ID list. + + Call **getAvailableIDs** to obtain the transliterator ID list. + An ID is in the **source-destination** format. For example, **ASCII-Latin** means to convert the transliterator ID from ASCII to Latin. + + ```js + let ids = I18n.Transliterator.getAvailableIDs(); // ids = ["ASCII-Latin", "Accents-Any", ... ], 671 languages in total + ``` + +3. Create a **Transliterator** object, and obtain the transliterated string. + + You can use the ID in the transliterator ID list as an input parameter of the **getInstance** API to create a **Transliterator** object. + Call **transform** to obtain the transliterated string. + + ```js + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); // Any-Latn means to convert any text to Latn text. + let transformText = transliterator.transform ("Hello"); // transformText = "nǐ hǎo" + ``` + +## Obtaining the Character Type + +[Unicode](../reference/apis/js-apis-i18n.md#unicode9) provides APIs to obtain character information, for example, whether a character is a digit or a space. + +### Available APIs + +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| Unicode | isDigit(char: string): boolean9+ | Checks whether the input character is a digit. | +| Unicode | isSpaceChar(char: string): boolean9+ | Checks whether the input character is a space. | +| Unicode | isWhitespace(char: string): boolean9+ | Checks whether the input character is a white space. | +| Unicode | isRTL(char: string): boolean9+ | Checks whether the input character is of the RTL language. | +| Unicode | isIdeograph(char: string): boolean9+ | Checks whether the input character is an ideographic character. | +| Unicode | isLetter(char: string): boolean9+ | Checks whether the input character is a letter. | +| Unicode | isLowerCase(char: string): boolean9+ | Checks whether the input character is a lowercase letter. | +| Unicode | isUpperCase(char: string): boolean9+ | Checks whether the input character is an uppercase letter. | +| Unicode | getType(char: string): string9+ | Obtains the type of a character.| ### How to Develop -1. Instantiate a **BreakIterator** object. +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' + ``` - Call the **getLineInstance** method to instantiate a **BreakIterator** object. +2. Check the input character has a certain attribute. + Check whether the input character is a digit. - ```js - var locale = "en-US" - var breakIterator = i18n.getLineInstance(locale); + ```js + let isDigit = I18n.Unicode.isDigit("1"); // isDigit = true + isDigit = I18n.Unicode.isDigit("a"); // isDigit = false ``` -2. Set and access the text that requires line breaking. + Check whether the input character is a space. - Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking. + ```js + let isSpaceChar = I18n.Unicode.isSpaceChar(" "); // isSpaceChar = true + isSpaceChar = I18n.Unicode.isSpaceChar("\n"); // isSpaceChar = false + ``` - - ```js - var text = "Apple is my favorite fruit"; - breakIterator.setLineBreakText(text); - var breakText = breakIterator.getLineBreakText(); + Check whether the input character is a white space. + + ```js + let isWhitespace = I18n.Unicode.isWhitespace(" "); // isWhitespace = true + isWhitespace = I18n.Unicode.isWhitespace("\n"); // isWhitespace = true + ``` + + Check whether the input character is of the RTL language. + + ```js + let isRTL = I18n.Unicode.isRTL(""); // isRTL = true (Arabic characters are written from left to right.) + isRTL = I18n.Unicode.isRTL("a"); // isRTL = false ``` -3. Obtain the current position of the **BreakIterator** object. + Check whether the input character is an ideographic character. - Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed. + ```js + let isIdeograph = I18n.Unicode.isIdeograph("Hello"); // isIdeograph = true + isIdeograph = I18n.Unicode.isIdeograph("a"); // isIdeograph = false + ``` + Check whether the input character is a letter. - ```js - var pos = breakIterator.current(); + ```js + let isLetter = I18n.Unicode.isLetter("a"); // isLetter = true + isLetter = I18n.Unicode.isLetter("."); // isLetter = false ``` -4. Set the position of a **BreakIterator** object. + Check whether the input character is a lowercase letter. - The following APIs are provided to adjust the **first**, **last**, **next**, **previous**, or **following** position of the **BreakIterator** object in the text to be processed. + ```js + let isLowerCase = I18n.Unicode.isLowerCase("a"); // isLetter = true + isLowerCase = I18n.Unicode.isLowerCase("A"); // isLetter = false + ``` - - ```js - var firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text. - var lastPos = breakIterator.last(); // Set a BreakIterator object to the last break point, that is, the position after the text end. - // Move a BreakIterator object forward or backward by a certain number of break points. - // If a positive number is input, move backward. If a negative number is input, move forward. If no value is input, move one position backward. - // When the object is moved out of the text length range, -1 is returned. - var nextPos = breakIterator.next(-2); - var previousPos = breakIterator.previous(); // Move a BreakIterator object to the previous break point. When the text length is out of the range, -1 is returned. - // Move a BreakIterator object to the break point following the position specified by offset. If the object is moved out of the text length range, -1 is returned. - var followingPos = breakIterator.following(10); + Check whether the input character is an uppercase letter. + + ```js + let isUpperCase = I18n.Unicode.isUpperCase("a"); // isUpperCase = false + isUpperCase = I18n.Unicode.isUpperCase("A"); // isUpperCase = true + ``` + +3. Obtain the character type. + + Call **getType** to obtain the character type. + + ```js + let type = I18n.Unicode.getType("a"); // type = U_LOWER_CASE_LETTER ``` -5. Determine whether a position is a break point. +## Obtaining the Sequence of Year, Month, and Day in a Date - Call the **isBoundary** method to determine whether a position is a break point. If yes, **true** is returned and the **BreakIterator** object is moved to this position. If no, **false** is returned and the **BreakIterator** object is moved to a break point after this position. +### Available APIs +| Class | API | Description | +| --------- | ---------------------------------------- | ------------------------------ | +| I18NUtil | getDateOrder(locale: string): string9+ | Checks the sequence of year, month, and day in a date. | + +### How to Develop - ```js - var isboundary = breakIterator.isBoundary(5); +1. Import the **i18n** module. + + ```js + import I18n from '@ohos.i18n' ``` - ``` \ No newline at end of file +2. Check the sequence of year, month, and day in a date. + + Call **getDateOrder** to obtain the sequence of year, month, and day in the date of the specified locale. + The API returns a string consisting of three parts, **y**, **L**, and **d**, which indicate the year, month, and day, respectively. The three parts are separated by using a hyphen (-), for example, **y-L-d**. + + ```js + let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d" indicates that the sequence of year, month, and day in Chinese is year-month-day. + ``` diff --git a/en/application-dev/internationalization/intl-guidelines.md b/en/application-dev/internationalization/intl-guidelines.md index f123a0b29a64a10b683f9fb90d163790e4f0524e..609af84500cecb0ce5bda8409216b6957182885f 100644 --- a/en/application-dev/internationalization/intl-guidelines.md +++ b/en/application-dev/internationalization/intl-guidelines.md @@ -1,38 +1,42 @@ -# Internationalization Development (Intl) +# intl Development -This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. For more details about APIs and their usage, see [Intl](../reference/apis/js-apis-intl.md). +The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. For more details about APIs and their usage, see [intl](../reference/apis/js-apis-intl.md). -> **NOTE** -> -> In the code snippets in this document, **intl** refers to the name of the imported module. +The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. ## Setting Locale Information -Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minimize locale information. - +[Locale](../reference/apis/js-apis-intl.md#locale) provides APIs to maximize or minimize the locale information. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Instantiates a **Locale** object. | -| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | -| ohos.intl | toString(): string | Converts locale information into a string. | -| ohos.intl | maximize(): Locale | Maximizes locale information. | -| ohos.intl | minimize(): Locale | Minimizes locale information. | - +| Locale | constructor()8+ | Instantiates a **Locale** object.| +| Locale | constructor(locale:string,options?:LocaleOptions) | Instantiates a **Locale** object based on the locale parameter and options.| +| Locale | toString():string | Converts locale information into a string.| +| Locale | maximize():Locale | Maximizes locale information.| +| Locale | minimize():Locale | Minimizes locale information.| ### How to Develop -1. Instantiate a **Locale** object. +1. Import the **intl** module. + + Importing an incorrect bundle can lead to unexpected API behavior. + + ```js + import Intl from '@ohos.intl' + ``` + +2. Instantiates a **Locale** object. - Create a **Locale** object by using the **Locale** constructor. This method receives a string representing the locale and an optional [Attributes](../reference/apis/js-apis-intl.md#localeoptions) list. + Create a **Locale** object using the **Locale** constructor. This API receives a string representing the locale and an optional [attribute](../reference/apis/js-apis-intl.md#localeoptions) list. (Note that **intl** is the name of the imported module.) A **Locale** object consists of four parts: language, script, region, and extension, which are separated by using a hyphen (-). - Language: mandatory. It is represented by a two-letter or three-letter code as defined in ISO-639. For example, **en** indicates English and **zh** indicates Chinese. - Script: optional. It is represented by a four-letter code as defined in ISO-15924. The first letter is in uppercase, and the remaining three letters are in lowercase. For example, **Hant** represents the traditional Chinese, and **Hans** represents the simplified Chinese. - Country or region: optional. It is represented by two-letter code as defined in ISO-3166. Both letters are in uppercase. For example, **CN** represents China, and **US** represents the United States. - - Extensions: optional. Each extension consists of two parts, key and value. Currently, the extensions listed in the following table are supported (see BCP 47 Extensions). Extensions can be in any sequence and are written in the format of **-key-value**. They are appended to the language, script, and region by using **-u**. For example, **zh-u-nu-latn-ca-chinese** indicates that the Latin numbering system and Chinese calendar system are used. Extensions can also be passed via the second parameter. + - Extensions: optional. Each extension consists of two parts, key and value. Currently, the extensions listed in the following table are supported (see BCP 47 Extensions). Extensions can be in any sequence and are written in the format of **-key-value**. They are appended to the language, script, and region by using **-u**. For example, **zh-u-nu-latn-ca-chinese** indicates that the latn digital system and chinese calendar system are used. Extensions can also be passed via the second parameter. | Extended Parameter ID| Description| | -------- | -------- | | ca | Calendar algorithm.| @@ -40,305 +44,346 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim | hc | Hour cycle.| | nu | Numbering system.| | kn | Whether numeric collation is used when sorting or comparing strings.| - | kf | Whether upper case or lower case is considered when sorting or comparing strings.| + | kf | Whether capitalization is considered when sorting or comparing strings.| ```js - var locale = "zh-CN"; - var options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"}; - var localeObj = new intl.Locale(locale, options); + let locale = "zh-CN"; + let options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"}; + let localeObj = new Intl.Locale(locale, options); ``` -2. Obtain the string representing a **Locale** object. +3. Obtain the string representing a **Locale** object. - Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options. - + Call **toString** to obtain the string representing a **Locale** object, including the language, region, and other options. + ```js - var localeStr = localeObj.toString(); + let localeStr = localeObj.toString(); // localeStr = "zh-CN-u-ca-chinese-co-pinyin-kf-false ``` -3. Maximize locale information. +4. Maximize locale information. - Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information. - + Call **maximize** to maximize locale information; that is, supplement the missing script and region information. + ```js - var maximizedLocale = localeObj.maximize(); + let maximizedLocale = localeObj.maximize(); + let maximizedLocaleStr = maximizedLocale.toString(); // localeStr = "zh-Hans-CN-u-ca-chinese-co-pinyin-kf-false ``` -4. Minimize locale information. +5. Minimize locale information. - Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information. - + Call **minimize** to minimize locale information; that is, delete the unnecessary script and region information. + ```js - var minimizedLocale = localeObj.minimize(); + let minimizedLocale = localeObj.minimize(); + let minimizedLocaleStr = minimizedLocale.toString(); // zh-u-ca-chinese-co-pinyin-kf-false ``` - ## Formatting the Date and Time -Use [DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) APIs to format the date and time for a specific locale. - +[DateTimeFormat](../reference/apis/js-apis-intl.md#datetimeformat) provides APIs to format the date and time for the specified locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **DateTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(date: Date): string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | formatRange(startDate: Date, endDate: Date): string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object. | -| ohos.intl | resolvedOptions(): DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object. | - +| DateTimeFormat | constructor()8+ | Creates a **DateTimeFormat** object.| +| DateTimeFormat | constructor(locale:string\|Array<string>,options?:DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes.| +| DateTimeFormat | format(date:Date):string | Calculates the date and time based on the locale and other formatting-related attributes of the **DateTimeFormat** object.| +| DateTimeFormat | formatRange(startDate:Date,endDate:Date):string | Calculates the period based on the locale and other formatting-related attributes of the **DateTimeFormat** object.| +| DateTimeFormat | resolvedOptions():DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object.| ### How to Develop -1. Instantiate a **DateTimeFormat** object. - - Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var dateTimeFormat = new intl.DateTimeFormat(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions). - +2. Instantiate a **DateTimeFormat** object. + + Use the default constructor of **DateTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **DateTimeFormat** object. + ```js - var options = {dateStyle: "full", timeStyle: "full"}; - var dateTimeFormat = new intl.DateTimeFormat("zh-CN", options); + let dateTimeFormat = new Intl.DateTimeFormat(); ``` -2. Format the date and time. - - Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. + Alternatively, use your own locale and formatting parameters to create a **DateTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [DateTimeOptions](../reference/apis/js-apis-intl.md#datetimeoptions). ```js - var date = new Date(); - var formatResult = dateTimeFormat.format(date); + let options = {dateStyle: "full", timeStyle: "full"}; + let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); ``` -3. Format a period. +3. Format the date and time. - Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. - + Call **format** to format a **Date** object. A string is returned as the formatting result. + ```js - var startDate = new Date(2021, 11, 17, 3, 24, 0); - var endDate = new Date(2021, 11, 18, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.formatRange(startDate, endDate); + let options = {dateStyle: "full", timeStyle: "full"}; + let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); + let date = new Date(2022, 12, 12, 12, 12, 12); + let formatResult = dateTimeFormat.format(date); // formatResult = "January 12, 2023, Thursday, 12:12:12 pm, China Standard Time" ``` -4. Obtain attributes of the **DateTimeFormat** object. +4. Format a period. - Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object. - + Call **formatRange** to format a period. This API requires the input of two **Date** objects, which respectively indicate the start date and end date of a period. A string is returned as the formatting result. + ```js - var options = dateTimeFormat.resolvedOptions(); + let startDate = new Date(2021, 11, 17, 3, 24, 0); + let endDate = new Date(2021, 11, 18, 3, 24, 0); + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formatRangeResult = datefmt.formatRange(startDate, endDate); // formatRangeResult = "17/12/2021-18/12/2021" ``` +5. Access the attributes of the **DateTimeFormat** object. -## Formatting Numbers + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **DateTimeFormat** object. + + ```js + let options = {dateStyle: "full", timeStyle: "full"}; + let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options); + let resolvedOptions = dateTimeFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "calendar": "gregorian", "dateStyle":"full", "timeStyle":"full", "timeZone": "CST"} + ``` -Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to format numbers for a specific locale. +## Number Formatting +[NumberFormat](../reference/apis/js-apis-intl.md#numberformat) provides APIs to implement the number formatting specific to a locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **NumberFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(number: number): string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object. | -| ohos.intl | resolvedOptions(): NumberOptions | Obtains attributes of the **NumberFormat** object. | - +| NumberFormat | constructor()8+ | Creates a **NumberFormat** object for the specified locale.| +| NumberFormat | constructor(locale:string\|Array<string>,options?:NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes.| +| NumberFormat | format(number:number):string | Calculates the number based on the locale and other formatting-related attributes of the **NumberFormat** object.| +| NumberFormat | resolvedOptions():NumberOptions | Obtains the attributes of the **NumberFormat** object.| ### How to Develop -1. Instantiate a **NumberFormat** object. - - Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **NumberFormat** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var numberFormat = new intl.NumberFormat(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions). - +2. Instantiate a **NumberFormat** object. + + Use the default constructor of **NumberFormat** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **NumberFormat** object (**intl** is the name of the imported module). + ```js - var options = {compactDisplay: "short", notation: "compact"}; - var numberFormat = new intl.NumberFormat("zh-CN", options); + let numberFormat = new Intl.NumberFormat(); ``` -2. Format a number. - - Call the **format** method to format a number. A string is returned as the formatting result. + Alternatively, use your own locale and formatting parameters to create a **NumberFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [NumberOptions](../reference/apis/js-apis-intl.md#numberoptions). ```js - var number = 1234.5678 - var formatResult = numberFormat.format(number); + let options = {compactDisplay: "short", notation: "compact"}; + let numberFormat = new Intl.NumberFormat("zh-CN", options); ``` -3. Obtain attributes of the **NumberFormat** object. +3. Format a number. - Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object. - + Call **format** to format a number. A string is returned as the formatting result. + ```js - var options = numberFormat.resolvedOptions(); + let options = {compactDisplay: "short", notation: "compact"}; + let numberFormat = new Intl.NumberFormat("zh-CN", options); + let number = 1234.5678 + let formatResult = numberFormat.format(number); // formatResult = "1235" ``` +4. Access the attributes of the **NumberFormat** object. -## Sorting Strings + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **NumberFormat** object. + + ```js + let options = {compactDisplay: "short", notation: "compact"}; + let numberFormat = new Intl.NumberFormat("zh-CN", options); + let resolvedOptions = numberFormat.resolvedOptions(); // resolvedOptions = {"locale": "zh-CN", "compactDisplay": "short", "notation": "compact", "numberingSystem": "Latn"} + ``` -Use [Collator](../reference/apis/js-apis-intl.md#collator8) APIs to sort strings based on a specific locale. Users in different regions have different preferences for string sorting. +## String Sorting +Users in different regions have different requirements for string sorting. [Collator](../reference/apis/js-apis-intl.md#collator8) provides APIs to sort character strings specific to a locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **Collator** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes. | -| ohos.intl | compare(first: string, second: string): number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | -| ohos.intl | resolvedOptions(): CollatorOptions8+ | Obtains attributes of the **Collator** object. | - +| Collator | constructor()8+ | Creates a **Collator** object.| +| Collator | constructor(locale:string\|Array<string>,options?:CollatorOptions)8+ | Creates a **Collator** object and sets the locale and other related attributes.| +| Collator | compare(first:string,second:string):number8+ | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object.| +| Collator | resolvedOptions():CollatorOptions8+ | Obtains the attributes of the **Collator** object.| ### How to Develop -1. Instantiate a **Collator** object. - - Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **Collator** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var collator = new intl.Collator(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions9). - +2. Instantiate a **Collator** object. + + Use the default constructor of **Collator** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **Collator** object (**intl** is the name of the imported module). + ```js - var collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); + let collator = new Intl.Collator(); ``` -2. Compare two strings. - - Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. This allows you to sort character strings based on the comparison result. + Alternatively, use your own locale and formatting parameters to create a **Collator** object. For a full list of parameters, see [CollatorOptions](../reference/apis/js-apis-intl.md#collatoroptions8). + The **sensitivity** parameter is used to specify the levels of differences that will be used for string comparison. The value **base** indicates that only characters are compared, but not the accent and capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **accent** indicates that the accent is considered, but not the capitalization. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **case** indicates that the capitalization is considered, but the accent. For example, 'a' != 'b', 'a' == '', 'a'=='A'. The value **variant** indicates that the accent and capitalization are considered. For example, 'a' != 'b', 'a' == '', 'a'=='A'. ```js - var str1 = "first string"; - var str2 = "second string"; - var compareResult = collator.compare(str1, str2); + let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"}); ``` -3. Obtain attributes of the **Collator** object. +3. Compare two strings. - Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object. - + Call **compare** to compare two input strings. This API returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. This allows you to sort character strings based on the comparison result. + ```js - var options = collator.resolvedOptions(); + let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"}); + let str1 = "first string"; + let str2 = "second string"; + let compareResult = collator.compare(str1, str2); // compareResult = -1 + str1 = "first"; + str2 = "First"; + compareResult = collator.compare(str1, str2); // compareResult = -1 ``` +4. Access the attributes of the **Collator** object. -## Determining the Singular-Plural Type + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **Collator** object. + + ```js + let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); + let options = collator.resolvedOptions(); // options = {"localeMatcher": "best fit", "locale": "zh-CN", "usage": "sort", "sensitivity": "variant", "ignorePunctuation": "false", "numeric": false, "caseFirst": "false", "collation": "default"} + ``` -Use [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) APIs to determine the singular-plural type for a specific locale. According to the grammar of certain languages, the singular or plural form of a noun depends on its preceding number. +## Determining the Singular-Plural Type +According to grammars in certain languages, the singular or plural form of a noun depends on the number prior to the noun. [PluralRules](../reference/apis/js-apis-intl.md#pluralrules8) provides APIs to determine the singular-plural type for a specific locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **PluralRules** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes. | -| ohos.intl | select(n: number): string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | +| PluralRules | constructor()8+ | Creates a **PluralRules** object.| +| PluralRules | constructor(locale:string\|Array<string>,options?:PluralRulesOptions)8+ | Creates a **PluralRules** object and sets the locale and other related attributes.| +| PluralRules | select(n:number):string8+ | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object.| ### How to Develop -1. Instantiate a **PluralRules** object. - - Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **PluralRules** object. +1. Import the **intl** module. + Importing an incorrect bundle can lead to unexpected API behavior. ```js - var pluralRules = new intl.PluralRules(); + import Intl from '@ohos.intl' ``` - Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions9). - +2. Instantiate a **PluralRules** object. + + Use the default constructor of **PluralRules** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **PluralRules** object (**intl** is the name of the imported module). + ```js - var pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); + let pluralRules = new Intl.PluralRules(); ``` -2. Determine the singular-plural type. - - Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. + Alternatively, use your own locale and formatting parameters to create a **PluralRules** object. For a full list of parameters, see [PluralRulesOptions](../reference/apis/js-apis-intl.md#pluralrulesoptions8). ```js - var number = 1234.5678 - var categoryResult = plurals.select(number); + let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); ``` +3. Determine the singular-plural type. -## Formatting the Relative Time + Call **select** to determine the singular-plural type for an input number. This API returns a string as the category of the input number, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. + + ```js + let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); + let number = 1234.5678 + let categoryResult = pluralRules.select(number); // categoryResult = "other" + ``` -Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) APIs to format the relative time for a specific locale. +## Formatting Relative Time +[RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) provides APIs to format the relative time for a specific locale. ### Available APIs -| Module | API | Description | +| Class| API| Description| | -------- | -------- | -------- | -| ohos.intl | constructor()8+ | Creates a **RelativeTimeFormat** object. | -| ohos.intl | constructor(locale: string \| Array<string>, options?: RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | -| ohos.intl | format(value: number, unit: string): string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | formatToParts(value: number, unit: string): Array<object>8+ | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | -| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions8+ | Obtains attributes of the **RelativeTimeFormat** object. | - +| RelativeTimeFormat | constructor()8+ | Creates a **RelativeTimeFormat** object.| +| RelativeTimeFormat | constructor(locale:string\|Array<string>,options?:RelativeTimeFormatInputOptions)8+ | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes.| +| RelativeTimeFormat | format(value:number,unit:string):string8+ | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object.| +| RelativeTimeFormat | formatToParts(value:number,unit:string):Array<object>8+ | Obtains each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object.| +| RelativeTimeFormat | resolvedOptions():RelativeTimeFormatResolvedOptions8+ | Obtains the attributes of the **RelativeTimeFormat** object.| ### How to Develop -1. Instantiate a **RelativeTimeFormat** object. +1. Import the **intl** module. - Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings, and set it as the locale in the **RelativeTimeFormat** object. + Importing an incorrect bundle can lead to unexpected API behavior. + + ```js + import Intl from '@ohos.intl' + ``` + +2. Instantiate a **RelativeTimeFormat** object. + Use the default constructor of **RelativeTimeFormat** to obtain the system default locale by accessing the system language and region settings and set it as the locale in the **RelativeTimeFormat** object (**intl** is the name of the imported module). ```js - var relativeTimeFormat = new intl.RelativeTimeFormat(); + let relativeTimeFormat = new Intl.RelativeTimeFormat(); ``` - Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions9). + Alternatively, use your own locale and formatting parameters to create a **RelativeTimeFormat** object. Formatting parameters are optional. For a full list of formatting parameters, see [RelativeTimeFormatInputOptions](../reference/apis/js-apis-intl.md#relativetimeformatinputoptions8). ```js - var relativeTimeFormat = new intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); ``` -2. Format the relative time. +3. Format the relative time. - Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result. - + Call **format** to format the relative time. This API receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. A string is returned as the formatting result. + ```js - var number = 2; - var unit = "year" - var formatResult = relativeTimeFormat.format(number, unit); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let number = 2; + let unit = "year" + let formatResult = relativeTimeFormat.format(number, unit); // 2 years later ``` -3. Obtain each part of the relative time format. +4. Obtain each part of the relative time format. - Upon obtaining each part of the relative time format, customize the relative time formatting result. - + On obtaining each part of the relative time format, customize the relative time formatting result. + ```js - var number = 2; - var unit = "year" - var formatResult = relativeTimeFormat.formatToParts(number, unit); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let number = 2; + let unit = "year" + let formatPartsResult = relativeTimeFormat.formatToParts(number, unit); // formatPartsResult = [{"type": "integer", "value": "2", "unit": "year"}, {"type":"literal", "value": "years later"}] ``` -4. Obtain attributes of the **RelativeTimeFormat** object. +5. Access the attributes of the **RelativeTimeFormat** object. - Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8). - + Call **resolvedOptions** to obtain an object that contains all related attributes and values of the **RelativeTimeFormat** object. For a full list of attributes, see [RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md#relativetimeformatresolvedoptions8). + ```js - var options = numberFormat.resolvedOptions(); + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"}); + let options = relativeTimeFormat.resolvedOptions(); // options = {"locale": "zh-CN", "style": "long", "numeric": "always", "numberingSystem": "latn"} ``` ## Samples diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 2a75e1015411c92c75f58d32dc236283fd24f266..cda33f5434360fe5ca3f21f9f2c0a04ad5b50474 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,15 +1,18 @@ # @ohos.i18n (Internationalization) -The **i18n** module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. -The [intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. +The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. +The [intl](js-apis-intl.md) module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities. + +> **NOTE** +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - This module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. For details about the basic i18n capabilities, see [intl](js-apis-intl.md). -> **NOTE** -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ```js -import i18n from '@ohos.i18n'; +import I18n from '@ohos.i18n'; ``` @@ -39,16 +42,16 @@ Obtains the localized script for the specified country. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var displayCountry = i18n.System.getDisplayCountry("zh-CN", "en-GB"); + let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China" } catch(error) { console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`) } @@ -78,16 +81,16 @@ Obtains the localized script for the specified language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var displayLanguage = i18n.System.getDisplayLanguage("zh", "en-GB"); + let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese } catch(error) { console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -109,16 +112,16 @@ Obtains the list of system languages. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLanguages = i18n.System.getSystemLanguages(); + let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ] } catch(error) { console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`) } @@ -134,9 +137,9 @@ Obtains the list of countries and regions supported for the specified language. **Parameters** -| Name | Type | Description | -| -------- | ------ | ----- | -| language | string | Language ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----- | +| language | string | Yes | Language ID.| **Return value** @@ -146,16 +149,16 @@ Obtains the list of countries and regions supported for the specified language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemCountries = i18n.System.getSystemCountries('zh'); + let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total } catch(error) { console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`) } @@ -184,16 +187,16 @@ Checks whether the system language matches the specified region. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var res = i18n.System.isSuggested('zh', 'CN'); + let res = I18n.System.isSuggested('zh', 'CN'); // res = true } catch(error) { console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`) } @@ -215,16 +218,16 @@ Obtains the system language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLanguage = i18n.System.getSystemLanguage(); + let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language. } catch(error) { console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -236,7 +239,7 @@ static setSystemLanguage(language: string): void Sets the system language. Currently, this API does not support real-time updating of the system language. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -244,22 +247,22 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| language | string | Yes | Language ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----- | +| language | string | Yes | Language ID.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemLanguage('zh'); + I18n.System.setSystemLanguage('zh'); // Set the current system language to zh. } catch(error) { console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -281,16 +284,16 @@ Obtains the system region. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemRegion = i18n.System.getSystemRegion(); + let systemRegion = I18n.System.getSystemRegion(); // Obtain the current system region. } catch(error) { console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) } @@ -302,7 +305,7 @@ static setSystemRegion(region: string): void Sets the system region. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -310,22 +313,22 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| region | string | Yes | Region ID.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----- | +| region | string | Yes | Region ID.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemRegion('CN'); + I18n.System.setSystemRegion('CN'); // Set the current system region to CN. } catch(error) { console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) } @@ -347,16 +350,16 @@ Obtains the system locale. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLocale = i18n.System.getSystemLocale(); + let systemLocale = I18n.System.getSystemLocale(); // Obtain the current system locale. } catch(error) { console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) } @@ -368,7 +371,7 @@ static setSystemLocale(locale: string): void Sets the system locale. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -376,22 +379,22 @@ This is a system API. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| locale | string | Yes | System locale ID, for example, **zh-CN**.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------- | +| locale | string | Yes | System locale ID, for example, **zh-CN**.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemLocale('zh-CN'); + I18n.System.setSystemLocale('zh-CN'); // Set the current system locale to zh-CN. } catch(error) { console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) } @@ -413,16 +416,16 @@ Checks whether the 24-hour clock is used. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var is24HourClock = i18n.System.is24HourClock(); + let is24HourClock = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled. } catch(error) { console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`) } @@ -434,7 +437,7 @@ static set24HourClock(option: boolean): void Sets the 24-hour clock. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -448,17 +451,17 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Set the system time to the 24-hour clock. try { - i18n.System.set24HourClock(true); + I18n.System.set24HourClock(true); } catch(error) { console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`) } @@ -470,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void Adds a preferred language to the specified position on the preferred language list. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -485,19 +488,19 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Add zh-CN to the preferred language list. - var language = 'zh-CN'; - var index = 0; + let language = 'zh-CN'; + let index = 0; try { - i18n.System.addPreferredLanguage(language, index); + I18n.System.addPreferredLanguage(language, index); // Add zh-CN to the first place in the preferred language list. } catch(error) { console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -509,7 +512,7 @@ static removePreferredLanguage(index: number): void Deletes a preferred language from the specified position on the preferred language list. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -523,18 +526,18 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Delete the first preferred language from the preferred language list. - var index = 0; + let index = 0; try { - i18n.System.removePreferredLanguage(index); + I18n.System.removePreferredLanguage(index); } catch(error) { console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -544,7 +547,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod static getPreferredLanguageList(): Array<string> -Obtains the list of preferred languages. +Obtains the preferred language list. **System capability**: SystemCapability.Global.I18n @@ -552,20 +555,20 @@ Obtains the list of preferred languages. | Type | Description | | ------------------- | --------- | -| Array<string> | List of preferred languages.| +| Array<string> | Preferred language list.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var preferredLanguageList = i18n.System.getPreferredLanguageList(); + let preferredLanguageList = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list. } catch(error) { console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`) } @@ -587,16 +590,16 @@ Obtains the first language in the preferred language list. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var firstPreferredLanguage = i18n.System.getFirstPreferredLanguage(); + let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list. } catch(error) { console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -618,16 +621,16 @@ Obtains the preferred language of an application. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var appPreferredLanguage = i18n.System.getAppPreferredLanguage(); + let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application. } catch(error) { console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -637,9 +640,9 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod static setUsingLocalDigit(flag: boolean): void -Sets whether to turn on the local digit switch. +Sets whether to enable the local digit switch. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -649,20 +652,20 @@ This is a system API. | Name | Type | Mandatory | Description | | ---- | ------- | ---- | ------------------------------- | -| flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.| +| flag | boolean | Yes | Whether to enable the local digit switch. The value **true** means to enable the local digit switch, and the value **false** indicates the opposite.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```ts try { - i18n.System.setUsingLocalDigit(true); + I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. } catch(error) { console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) } @@ -684,23 +687,23 @@ Checks whether the local digit switch is turned on. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```ts try { - var status = i18n.System.getUsingLocalDigit(); + let status = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled. } catch(error) { console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) } ``` -## i18n.isRTL7+ +## I18n.isRTL7+ isRTL(locale: string): boolean @@ -710,9 +713,9 @@ Checks whether the localized script for the specified language is displayed from **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ----- | ----- | -| locale | string | Yes | Locale ID.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| locale | string | Yes | Locale ID.| **Return value** @@ -727,7 +730,7 @@ Checks whether the localized script for the specified language is displayed from ``` -## i18n.getCalendar8+ +## I18n.getCalendar8+ getCalendar(locale: string, type? : string): Calendar @@ -750,7 +753,7 @@ Obtains a **Calendar** object. **Example** ```js - i18n.getCalendar("zh-Hans", "gregory"); + I18n.getCalendar("zh-Hans", "chinese"); // Obtain the Calendar object for the Chinese lunar calendar. ``` @@ -773,8 +776,8 @@ Sets the date for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); - var date = new Date(2021, 10, 7, 8, 0, 0, 0); + let calendar = I18n.getCalendar("en-US", "gregory"); + let date = new Date(2021, 10, 7, 8, 0, 0, 0); calendar.setTime(date); ``` @@ -795,7 +798,7 @@ Sets the date and time for this **Calendar** object. The value is represented by **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); + let calendar = I18n.getCalendar("en-US", "gregory"); calendar.setTime(10540800000); ``` @@ -821,7 +824,7 @@ Sets the year, month, day, hour, minute, and second for this **Calendar** object **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 ``` @@ -842,7 +845,7 @@ Sets the time zone of this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); ``` @@ -863,9 +866,9 @@ Obtains the time zone of this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); - calendar.getTimeZone(); // Asia/Shanghai" + let timezone = calendar.getTimeZone(); // timezone = "Asia/Shanghai" ``` @@ -885,8 +888,8 @@ Obtains the start day of a week for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); - calendar.getFirstDayOfWeek(); + let calendar = I18n.getCalendar("en-US", "gregory"); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 ``` @@ -906,8 +909,9 @@ Sets the start day of a week for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); - calendar.setFirstDayOfWeek(0); + let calendar = I18n.getCalendar("zh-Hans"); + calendar.setFirstDayOfWeek(3); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3 ``` @@ -927,8 +931,8 @@ Obtains the minimum number of days in the first week of a year. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); - calendar.getMinimalDaysInFirstWeek(); + let calendar = I18n.getCalendar("zh-Hans"); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1 ``` @@ -948,8 +952,9 @@ Sets the minimum number of days in the first week of a year. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setMinimalDaysInFirstWeek(3); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 ``` @@ -975,9 +980,9 @@ Obtains the value of the specified field in the **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 - calendar.get("hour_of_day"); // 8 + let hourOfDay = calendar.get("hour_of_day"); // hourOfDay = 8 ``` @@ -1003,8 +1008,8 @@ Obtains the **Calendar** object name displayed for the specified locale. **Example** ```js - var calendar = i18n.getCalendar("en-US", "buddhist"); - calendar.getDisplayName("zh"); // Obtain the name of the Buddhist calendar in zh. + let calendar = I18n.getCalendar("en-US", "buddhist"); + let calendarName = calendar.getDisplayName("zh"); // calendarName = "Buddhist Calendar" ``` @@ -1030,10 +1035,10 @@ Checks whether the specified date in this **Calendar** object is a weekend. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00 calendar.isWeekend(); // false - var date = new Date(2011, 11, 6, 9, 0, 0); + let date = new Date(2011, 11, 6, 9, 0, 0); calendar.isWeekend(date); // true ``` @@ -1058,7 +1063,7 @@ Creates a **PhoneNumberFormat** object. **Example** ```js - var phoneNumberFormat= new i18n.PhoneNumberFormat("CN", {"type": "E164"}); + let phoneNumberFormat= new I18n.PhoneNumberFormat("CN", {"type": "E164"}); ``` @@ -1084,8 +1089,8 @@ Checks whether the format of the specified phone number is valid. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.isValidNumber("15812312312"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let isValidNumber = phonenumberfmt.isValidNumber("15812312312"); // isValidNumber = true ``` @@ -1111,8 +1116,8 @@ Formats a phone number. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.format("15812312312"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let formattedPhoneNumber = phonenumberfmt.format("15812312312"); // formattedPhoneNumber = "158 1231 2312" ``` @@ -1139,8 +1144,8 @@ Obtains the home location of a phone number. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.getLocationName("15812312345", "zh-CN"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let locationName = phonenumberfmt.getLocationName("15812312345", "zh-CN"); // locationName = "Zhanjiang, Guangdong Province" ``` @@ -1150,7 +1155,7 @@ Defines the options for this PhoneNumberFormat object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | | type | string | Yes | Yes | Format type of a phone number. The available options are as follows: E164, INTERNATIONAL, NATIONAL, and RFC3966.| @@ -1161,7 +1166,7 @@ Defines the measurement unit information. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------- | ------ | ---- | ---- | ---------------------------------------- | | unit | string | Yes | Yes | Name of the measurement unit, for example, **meter**, **inch**, or **cup**.| | measureSystem | string | Yes | Yes | Measurement system. The value can be **SI**, **US**, or **UK**.| @@ -1189,7 +1194,7 @@ Creates an **IndexUtil** object. **Example** ```js - var indexUtil= i18n.getInstance("zh-CN"); + let indexUtil= I18n.getInstance("zh-CN"); ``` @@ -1212,8 +1217,10 @@ Obtains the index list for this **locale** object. **Example** ```js - var indexUtil = i18n.getInstance("zh-CN"); - var indexList = indexUtil.getIndexList(); + let indexUtil = I18n.getInstance("zh-CN"); + // indexList = [ "...", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", + // "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "..." ] + let indexList = indexUtil.getIndexList(); ``` @@ -1233,7 +1240,7 @@ Adds the index of the new **locale** object to the index list. **Example** ```js - var indexUtil = i18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); indexUtil.addLocale("en-US"); ``` @@ -1260,12 +1267,12 @@ Obtains the index of a text object. **Example** ```js - var indexUtil= i18n.getInstance("zh-CN"); - indexUtil.getIndex("hi"); // Return hi. + let indexUtil= I18n.getInstance("zh-CN"); + let index = indexUtil.getIndex("hi"); // index = "H" ``` -## i18n.getLineInstance8+ +## I18n.getLineInstance8+ getLineInstance(locale: string): BreakIterator @@ -1287,7 +1294,7 @@ Obtains a [BreakIterator](#breakiterator8) object for text segmentation. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); ``` @@ -1310,8 +1317,8 @@ Sets the text to be processed by the [BreakIterator](#breakiterator8) object. **Example** ```js - var iterator = i18n.getLineInstance("en"); - iterator.setLineBreakText("Apple is my favorite fruit."); + let iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit ."); // Set a short sentence as the text to be processed by the BreakIterator object. ``` @@ -1331,9 +1338,9 @@ Obtains the text being processed by the [BreakIterator](#breakiterator8) object. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.getLineBreakText(); // Apple is my favorite fruit. + let breakText = iterator.getLineBreakText(); // breakText = "Apple is my favorite fruit." ``` @@ -1353,9 +1360,9 @@ Obtains the position of the [BreakIterator](#breakiterator8) object in the text **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.current(); // 0 + let currentPos = iterator.current(); // currentPos = 0 ``` @@ -1375,9 +1382,9 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = i18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 + let firstPos = iterator.first(); // firstPos = 0 ``` @@ -1397,9 +1404,9 @@ Puts the [BreakIterator](#breakiterator8) object to the last text boundary, whic **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.last(); // 27 + let lastPos = iterator.last(); // lastPos = 27 ``` @@ -1425,11 +1432,11 @@ Moves the [BreakIterator](#breakiterator8) object backward by the specified numb **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 - iterator.next(); // 6 - iterator.next(10); // -1 + let pos = iterator.first(); // pos = 0 + pos = iterator.next(); // pos = 6 + pos = iterator.next(10); // pos = -1 ``` @@ -1449,11 +1456,11 @@ Moves the [BreakIterator](#breakiterator8) object to the previous text boundary. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 - iterator.next(3); // 12 - iterator.previous(); // 9 + let pos = iterator.first(); // pos = 0 + pos = iterator.next(3); // pos = 12 + pos = iterator.previous(); // pos = 9 ``` @@ -1479,11 +1486,11 @@ Moves the [BreakIterator](#breakiterator8) object to the text boundary after the **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.following(0); // 6 - iterator.following(100); // -1 - iterator.current(); // 27 + let pos = iterator.following(0); // pos = 6 + pos = iterator.following(100); // pos = -1 + pos = iterator.current(); // pos = 27 ``` @@ -1509,14 +1516,14 @@ Checks whether the position specified by the offset is a text boundary. If **tru **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.isBoundary(0); // true; - iterator.isBoundary(5); // false; + let isBoundary = iterator.isBoundary(0); // isBoundary = true; + isBoundary = iterator.isBoundary(5); // isBoundary = false; ``` -## i18n.getTimeZone7+ +## I18n.getTimeZone7+ getTimeZone(zoneID?: string): TimeZone @@ -1538,7 +1545,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID. **Example** ```js - var timezone = i18n.getTimeZone(); + let timezone = I18n.getTimeZone(); ``` @@ -1561,8 +1568,8 @@ Obtains the ID of the specified **TimeZone** object. **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getID(); + let timezone = I18n.getTimeZone(); + let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai" ``` @@ -1570,7 +1577,7 @@ Obtains the ID of the specified **TimeZone** object. getDisplayName(locale?: string, isDST?: boolean): string -Obtains the representation of a **TimeZone** object in the specified locale. +Obtains the localized representation of the time zone. **System capability**: SystemCapability.Global.I18n @@ -1589,8 +1596,8 @@ Obtains the representation of a **TimeZone** object in the specified locale. **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getDisplayName("zh-CN", false); + let timezone = I18n.getTimeZone(); + let timezoneName = timezone.getDisplayName("zh-CN", false); // timezoneName = "China Standard Time" ``` @@ -1610,8 +1617,8 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getRawOffset(); + let timezone = I18n.getTimeZone(); + let offset = timezone.getRawOffset(); // offset = 28800000 ``` @@ -1631,8 +1638,8 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getOffset(1234567890); + let timezone = I18n.getTimeZone(); + let offset = timezone.getOffset(1234567890); // offset = 28800000 ``` @@ -1652,7 +1659,8 @@ Obtains the list of time zone IDs supported by the system. **Example** ```ts - var ids = i18n.TimeZone.getAvailableIDs(); + // ids = ["America/Adak", "America/Anchorage", "America/Bogota", "America/Denver", "America/Los_Angeles", "America/Montevideo", "America/Santiago", "America/Sao_Paulo", "Asia/Ashgabat", "Asia/Hovd", "Asia/Jerusalem", "Asia/Magadan", "Asia/Omsk", "Asia/Shanghai", "Asia/Tokyo", "Asia/Yerevan", "Atlantic/Cape_Verde", "Australia/Lord_Howe", "Europe/Dublin", "Europe/London", "Europe/Moscow", "Pacific/Auckland", "Pacific/Easter", "Pacific/Pago-Pago"], 24 time zones supported in total + let ids = I18n.TimeZone.getAvailableIDs(); ``` @@ -1672,7 +1680,8 @@ Obtains the list of time zone city IDs supported by the system. **Example** ```ts - var cityIDs = i18n.TimeZone.getAvailableZoneCityIDs(); + // cityIDs = ["Auckland", "Magadan", "Lord Howe Island", "Tokyo", "Shanghai", "Hovd", "Omsk", "Ashgabat", "Yerevan", "Moscow", "Tel Aviv", "Dublin", "London", "Praia", "Montevideo", "Brasília", "Santiago", "Bogotá", "Easter Island", "Salt Lake City", "Los Angeles", "Anchorage", "Adak", "Pago Pago"], 24 time zone cities supported in total + let cityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); ``` @@ -1680,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system. static getCityDisplayName(cityID: string, locale: string): string -Obtains the localized display of a time zone city in the specified locale. +Obtains the localized representation of a time zone city in the specified locale. **System capability**: SystemCapability.Global.I18n @@ -1699,7 +1708,7 @@ Obtains the localized display of a time zone city in the specified locale. **Example** ```ts - var displayName = i18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); + let displayName = I18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); // displayName = "Shanghai (China)" ``` @@ -1725,7 +1734,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone city ID **Example** ```ts - var timezone = i18n.TimeZone.getTimezoneFromCity("Shanghai"); + let timezone = I18n.TimeZone.getTimezoneFromCity("Shanghai"); ``` @@ -1748,7 +1757,9 @@ Obtains a list of IDs supported by the **Transliterator** object. **Example** ```ts - i18n.Transliterator.getAvailableIDs(); + // ids = ["ASCII-Latin", "Accents-Any", "Amharic-Latin/BGN", ...], 671 IDs supported in total + // Each ID consists of two parts separated by a hyphen (-). The format is source-destination. + let ids = I18n.Transliterator.getAvailableIDs(); ``` @@ -1774,7 +1785,7 @@ Creates a **Transliterator** object. **Example** ```ts - var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); ``` @@ -1800,8 +1811,8 @@ Converts the input string from the source format to the target format. **Example** ```ts - var transliterator = i18n.Transliterator.getInstance("Any-Latn"); - transliterator.transform ("China"); + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); + let res = transliterator.transform("China"); // res = "zhōng guó" ``` @@ -1830,7 +1841,7 @@ Checks whether the input character string is composed of digits. **Example** ```js - var isdigit = i18n.Unicode.isDigit("1"); // Return true. + let isdigit = I18n.Unicode.isDigit("1"); // isdigit = true ``` @@ -1856,7 +1867,7 @@ Checks whether the input character is a space. **Example** ```js - var isspacechar = i18n.Unicode.isSpaceChar("a"); // Return false. + let isspacechar = I18n.Unicode.isSpaceChar("a"); // isspacechar = false ``` @@ -1882,7 +1893,7 @@ Checks whether the input character is a white space. **Example** ```js - var iswhitespace = i18n.Unicode.isWhitespace("a"); // Return false. + let iswhitespace = I18n.Unicode.isWhitespace("a"); // iswhitespace = false ``` @@ -1908,7 +1919,7 @@ Checks whether the input character is of the right to left (RTL) language. **Example** ```js - var isrtl = i18n.Unicode.isRTL("a"); // Return false. + let isrtl = I18n.Unicode.isRTL("a"); // isrtl = false ``` @@ -1934,7 +1945,7 @@ Checks whether the input character is an ideographic character. **Example** ```js - var isideograph = i18n.Unicode.isIdeograph("a"); // Return false. + let isideograph = I18n.Unicode.isIdeograph("a"); // isideograph = false ``` @@ -1960,7 +1971,7 @@ Checks whether the input character is a letter. **Example** ```js - var isletter = i18n.Unicode.isLetter("a"); // Return true. + let isletter = I18n.Unicode.isLetter("a"); // isletter = true ``` @@ -1986,7 +1997,7 @@ Checks whether the input character is a lowercase letter. **Example** ```js - var islowercase = i18n.Unicode.isLowerCase("a"); // Return true. + let islowercase = I18n.Unicode.isLowerCase("a"); // islowercase = true ``` @@ -2012,7 +2023,7 @@ Checks whether the input character is an uppercase letter. **Example** ```js - var isuppercase = i18n.Unicode.isUpperCase("a"); // Return false. + let isuppercase = I18n.Unicode.isUpperCase("a"); // isuppercase = false ``` @@ -2038,7 +2049,7 @@ Obtains the type of the input character string. **Example** ```js - var type = i18n.Unicode.getType("a"); + let type = I18n.Unicode.getType("a"); // type = "U_LOWERCASE_LETTER" ``` @@ -2071,7 +2082,7 @@ Converts one measurement unit into another and formats the unit based on the spe **Example** ```js - i18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); + let res = I18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); // res = 236.588 liters ``` @@ -2097,11 +2108,11 @@ Obtains the sequence of the year, month, and day in the specified locale. **Example** ```js - i18n.I18NUtil.getDateOrder("zh-CN"); + let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d" ``` -## i18n.getDisplayCountry(deprecated) +## I18n.getDisplayCountry(deprecated) getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string @@ -2127,12 +2138,12 @@ This API is deprecated since API version 9. You are advised to use [System.getDi **Example** ```js - i18n.getDisplayCountry("zh-CN", "en-GB", true); - i18n.getDisplayCountry("zh-CN", "en-GB"); + let countryName = I18n.getDisplayCountry("zh-CN", "en-GB", true); // countryName = true + countryName = I18n.getDisplayCountry("zh-CN", "en-GB"); // countryName = true ``` -## i18n.getDisplayLanguage(deprecated) +## I18n.getDisplayLanguage(deprecated) getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string @@ -2158,12 +2169,12 @@ This API is deprecated since API version 9. You are advised to use [System.getDi **Example** ```js - i18n.getDisplayLanguage("zh", "en-GB", true); - i18n.getDisplayLanguage("zh", "en-GB"); + let languageName = I18n.getDisplayLanguage("zh", "en-GB", true); // languageName = "Chinese" + languageName = I18n.getDisplayLanguage("zh", "en-GB"); // languageName = "Chinese" ``` -## i18n.getSystemLanguage(deprecated) +## I18n.getSystemLanguage(deprecated) getSystemLanguage(): string @@ -2181,11 +2192,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemLanguage(); + let systemLanguage = I18n.getSystemLanguage(); // Obtain the current system language. ``` -## i18n.getSystemRegion(deprecated) +## I18n.getSystemRegion(deprecated) getSystemRegion(): string @@ -2203,11 +2214,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemRegion(); + let region = I18n.getSystemRegion(); // Obtain the current system region. ``` -## i18n.getSystemLocale(deprecated) +## I18n.getSystemLocale(deprecated) getSystemLocale(): string @@ -2225,11 +2236,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemLocale(); + let locale = I18n.getSystemLocale (); // Obtain the system locale. ``` -## i18n.is24HourClock(deprecated) +## I18n.is24HourClock(deprecated) is24HourClock(): boolean @@ -2247,11 +2258,11 @@ This API is deprecated since API version 9. You are advised to use [System.is24H **Example** ```js - var is24HourClock = i18n.is24HourClock(); + let is24HourClock = I18n.is24HourClock(); ``` -## i18n.set24HourClock(deprecated) +## I18n.set24HourClock(deprecated) set24HourClock(option: boolean): boolean @@ -2278,11 +2289,11 @@ This API is deprecated since API version 9. You are advised to use [System.set24 **Example** ```js // Set the system time to the 24-hour clock. - var success = i18n.set24HourClock(true); + let success = I18n.set24HourClock(true); ``` -## i18n.addPreferredLanguage(deprecated) +## I18n.addPreferredLanguage(deprecated) addPreferredLanguage(language: string, index?: number): boolean @@ -2310,13 +2321,13 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js // Add zh-CN to the preferred language list. - var language = 'zh-CN'; - var index = 0; - var success = i18n.addPreferredLanguage(language, index); + let language = 'zh-CN'; + let index = 0; + let success = I18n.addPreferredLanguage(language, index); ``` -## i18n.removePreferredLanguage(deprecated) +## I18n.removePreferredLanguage(deprecated) removePreferredLanguage(index: number): boolean @@ -2343,16 +2354,16 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js // Delete the first preferred language from the preferred language list. - var index = 0; - var success = i18n.removePreferredLanguage(index); + let index = 0; + let success = I18n.removePreferredLanguage(index); ``` -## i18n.getPreferredLanguageList(deprecated) +## I18n.getPreferredLanguageList(deprecated) getPreferredLanguageList(): Array<string> -Obtains the list of preferred languages. +Obtains the preferred language list. This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead. @@ -2362,15 +2373,15 @@ This API is supported since API version 8 and is deprecated since API version 9. | Type | Description | | ------------------- | --------- | -| Array<string> | List of preferred languages.| +| Array<string> | Preferred language list.| **Example** ```js - var preferredLanguageList = i18n.getPreferredLanguageList(); + let preferredLanguageList = I18n.getPreferredLanguageList(); // Obtain the preferred language list. ``` -## i18n.getFirstPreferredLanguage(deprecated) +## I18n.getFirstPreferredLanguage(deprecated) getFirstPreferredLanguage(): string @@ -2388,7 +2399,7 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js - var firstPreferredLanguage = i18n.getFirstPreferredLanguage(); + let firstPreferredLanguage = I18n.getFirstPreferredLanguage(); ``` diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 2034cae2ba7d64c6f593f937a4c944e39e5ac04c..d4f3449adae43eed9b19236aec0d0308feed89e8 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,20 +1,20 @@ # @ohos.intl (Internationalization) -The **intl** module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. +The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. +The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities. -The [i18n](js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - This module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n interfaces defined in ECMA 402. For details about the enhanced i18n capabilities, see [i18n](js-apis-i18n.md). ## Modules to Import -``` +```js import Intl from '@ohos.intl'; ``` - +Importing an incorrect bundle can lead to unexpected API behavior. ## Locale @@ -23,16 +23,16 @@ import Intl from '@ohos.intl'; **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | | language | string | Yes | No | Language associated with the locale, for example, **zh**. | | script | string | Yes | No | Script type of the language, for example, **Hans**. | | region | string | Yes | No | Region associated with the locale, for example, **CN**. | | baseName | string | Yes | No | Basic key information about the locale, which consists of the language, script, and region, for example, **zh-Hans-CN**. | | caseFirst | string | Yes | No | Whether case is taken into account for the locale's collation rules. The value can be **upper**, **lower**, or **false**.| -| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| +| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, or **islamicc**.| | collation | string | Yes | No | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, **h24**.| +| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, or **h24**.| | numberingSystem | string | Yes | No | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | numeric | boolean | Yes | No | Whether to apply special collation rules for numeric characters. | @@ -41,13 +41,16 @@ import Intl from '@ohos.intl'; constructor() -Creates a Locale object. +Creates a **Locale** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var locale = new Intl.Locale(); + ```js + // The default constructor uses the current system locale to create a Locale object. + let locale = new Intl.Locale() + // Return the current system locale. + let localeID = locale.toString() ``` @@ -55,20 +58,22 @@ Creates a Locale object. constructor(locale: string, options?: LocaleOptions) -Creates a Locale object. +Creates a **Locale** object. **System capability**: SystemCapability.Global.I18n **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------- | ---- | ---------------------------- | -| locale | string | Yes | A string containing locale information, including the language, optional script, and region.| +| Name | Type | Mandatory | Description | +| -------------------- | -------------------------------- | ---- | ---------------------------- | +| locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).| | options9+ | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. | **Example** - ``` - var locale = new Intl.Locale("zh-CN"); + ```js + // Create a Locale object named zh-CN. + let locale = new Intl.Locale("zh-CN") + let localeID = locale.toString() // localeID = "zh-CN" ``` @@ -76,20 +81,21 @@ Creates a Locale object. toString(): string -Converts locale information to a string. +Obtains the string representation of a **Locale** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ------ | ----------- | -| string | String containing locale information.| +| string | String representation of the **Locale** object.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.toString(); + ```js + // Create a Locale object named en-GB. + let locale = new Intl.Locale("en-GB"); + let localeID = locale.toString(); // localeID = "en-GB" ``` @@ -101,16 +107,25 @@ Maximizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ----------------- | ---------- | | [Locale](#locale) | **Locale** object with the maximized information.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.maximize(); + ```js + // Create a Locale object named zh. + let locale = new Intl.Locale("zh"); + // Complete the script and region of the Locale object. + let maximizedLocale = locale.maximize(); + let localeID = maximizedLocale.toString(); // localeID = "zh-Hans-CN" + + // Create a Locale object named en-US. + locale = new Intl.Locale("en-US"); + // Complete the script of the Locale object. + maximizedLocale = locale.maximize(); + localeID = maximizedLocale.toString(); // localeID = "en-Latn-US" ``` @@ -122,16 +137,25 @@ Minimizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ----------------- | ---------- | | [Locale](#locale) | **Locale** object with the minimized information.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.minimize(); + ```js + // Create a Locale object named zh-Hans-CN. + let locale = new Intl.Locale("zh-Hans-CN"); + // Remove the script and region of the Locale object. + let minimizedLocale = locale.minimize(); + let localeID = minimizedLocale.toString(); // localeID = "zh" + + // Create a Locale object named en-US. + locale = new Intl.Locale("en-US"); + // Remove the region of the Locale object. + minimizedLocale = locale.minimize(); + localeID = minimizedLocale.toString(); // localeID = "en" ``` @@ -141,11 +165,11 @@ Represents the locale options. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | -| calendar | string | Yes | Yes | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| -| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**,**search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| calendar | string | Yes | Yes | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, or **islamicc**.| +| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, or **h24**.| | numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | numeric | boolean | Yes | Yes | Whether to use the 12-hour clock. | | caseFirst | string | Yes | Yes | Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| @@ -163,8 +187,9 @@ Creates a **DateTimeOptions** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var datefmt= new Intl.DateTimeFormat(); + ```js + // Use the current system locale to create a DateTimeFormat object. + let datefmt= new Intl.DateTimeFormat(); ``` @@ -178,20 +203,22 @@ Creates a **DateTimeOptions** object for the specified locale. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| Name | Type | Mandatory | Description | +| -------------------- | ------------------------------------ | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. | **Example** - ``` - var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); + ```js + // Use locale zh-CN to create a DateTimeFormat object. Set dateStyle to full and timeStyle to medium. + let datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); ``` **Example** - ``` - var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); + ```js + // Use the locale list ["ban", "zh"] to create a DateTimeFormat object. Because ban is an invalid locale ID, locale zh is used to create the DateTimeFormat object. + let datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); ``` @@ -209,17 +236,22 @@ Formats the specified date and time. | ---- | ---- | ---- | ------- | | date | Date | Yes | Date and time to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | ------------ | | string | A string containing the formatted date and time.| **Example** - ``` - var date = new Date(2021, 11, 17, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.format(date); + ```js + let date = new Date(2021, 11, 17, 3, 24, 0); + // Use locale en-GB to create a DateTimeFormat object. + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formattedDate = datefmt.format(date); // formattedDate "17/12/2021" + + // Use locale en-GB to create a DateTimeFormat object. Set dateStyle to full and timeStyle to medium. + datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); + formattedDate = datefmt.format(date); // formattedDate "Friday, 17 December 2021 at 03:24:00" ``` @@ -238,18 +270,19 @@ Formats the specified date range. | startDate | Date | Yes | Start date and time to be formatted.| | endDate | Date | Yes | End date and time to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | -------------- | | string | A string containing the formatted date and time range.| **Example** - ``` - var startDate = new Date(2021, 11, 17, 3, 24, 0); - var endDate = new Date(2021, 11, 18, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.formatRange(startDate, endDate); + ```js + let startDate = new Date(2021, 11, 17, 3, 24, 0); + let endDate = new Date(2021, 11, 18, 3, 24, 0); + // Use locale en-GB to create a DateTimeFormat object. + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formattedDateRange = datefmt.formatRange(startDate, endDate); // formattedDateRange = "17/12/2021-18/12/2021" ``` @@ -261,16 +294,19 @@ Obtains the formatting options for **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ----------------------------------- | ----------------------------- | +| Type | Description | +| ------------------------------------ | ----------------------------- | | [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.| **Example** - ``` - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.resolvedOptions(); + ```js + let datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); + // Obtain the options of the DateTimeFormat object. + let options = datefmt.resolvedOptions(); + let dateStyle = options.dateStyle; // dateStyle = "full" + let timeStyle = options.timeStyle; // timeStyle = "medium" ``` @@ -280,12 +316,12 @@ Provides the options for the **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | | locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | | dateStyle | string | Yes | Yes | Date display format. The value can be **long**, **short**, **medium**, or **full**.| | timeStyle | string | Yes | Yes | Time display format. The value can be **long**, **short**, **medium**, or **full**.| -| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, or **h24**.| | timeZone | string | Yes | Yes | Time zone represented by a valid IANA time zone ID. | | numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | hour12 | boolean | Yes | Yes | Whether to use the 12-hour clock. | @@ -315,8 +351,9 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var numfmt = new Intl.NumberFormat(); + ```js + // Use the current system locale to create a NumberFormat object. + let numfmt = new Intl.NumberFormat(); ``` @@ -328,15 +365,17 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n -Parameters -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | -------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. | **Example** - ``` - var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); + ```js + // Use locale en-GB to create a NumberFormat object. Set style to decimal and notation to scientific. + let numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); ``` @@ -354,7 +393,7 @@ Formats a number. | ------ | ------ | ---- | ---- | | number | number | Yes | Number to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------- | @@ -362,9 +401,10 @@ Formats a number. **Example** - ``` - var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); - numfmt.format(1223); + ```js + // Use locale list ["en-GB", "zh"] to create a NumberFormat object. Because en-GB is a valid locale ID, it is used to create the NumberFormat object. + let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + let formattedNumber = numfmt.format(1223); // formattedNumber = 1.223E3 ``` @@ -376,27 +416,30 @@ Obtains the options of the **NumberFormat** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ------------------------------- | --------------------------- | +| Type | Description | +| -------------------------------- | --------------------------- | | [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.| **Example** - ``` - var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); - numfmt.resolvedOptions(); + ```js + let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + // Obtain the options of the NumberFormat object. + let options = numfmt.resolvedOptions(); + let style = options.style; // style = decimal + let notation = options.notation // notation = scientific ``` ## NumberOptions6+ -Provides the device capability. +Defines the device capability. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------------------ | ------- | ---- | ---- | ---------------------------------------- | | locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | | currency | string | Yes | Yes | Currency unit, for example, **EUR**, **CNY**, or **USD**. | @@ -426,13 +469,14 @@ Provides the device capability. constructor() -Creates a Collator object. +Creates a **Collator** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var collator = new Intl.Collator(); + ```js + // Use the system locale to create a Collator object. + let collator = new Intl.Collator(); ``` @@ -440,20 +484,21 @@ Creates a Collator object. constructor(locale: string | Array<string>, options?: CollatorOptions) -Creates a Collator object. +Creates a **Collator** object. **System capability**: SystemCapability.Global.I18n **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| Name | Type | Mandatory | Description | +| -------------------- | ------------------------------------ | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. | **Example** - ``` - var collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); + ```js + // Use locale zh-CN to create a Collator object. Set localeMatcher to lookup and usage to sort. + let collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); ``` @@ -472,16 +517,18 @@ Compares two strings based on the sorting policy of the **Collator** object. | first | string | Yes | First string to compare. | | second | string | Yes | Second string to compare.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------------------------------------- | | number | Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is **0**, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.| **Example** - ``` - var collator = new Intl.Collator("zh-Hans"); - collator.compare("first", "second"); + ```js + // Use locale en-GB to create a Collator object. + let collator = new Intl.Collator("en-GB"); + // Compare the sequence of the first and second strings. + let compareResult = collator.compare("first", "second"); // compareResult = -1 ``` @@ -493,17 +540,19 @@ Returns properties reflecting the locale and collation options of a **Collator** **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ----------------------------------- | ----------------- | +| Type | Description | +| ------------------------------------ | ----------------- | | [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.| **Example** - - ``` - var collator = new Intl.Collator("zh-Hans"); - var options = collator.resolvedOptions(); + ```js + let collator = new Intl.Collator("zh-Hans", { usage: 'sort', ignorePunctuation: true }); + // Obtain the options of the Collator object. + let options = collator.resolvedOptions(); + let usage = options.usage; // usage = "sort" + let ignorePunctuation = options.ignorePunctuation // ignorePunctuation = true ``` @@ -513,11 +562,11 @@ Represents the properties of a **Collator** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ----------------- | ------- | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | usage | string | Yes | Yes | Whether the comparison is for sorting or for searching. The value can be **sort** or **search**. | -| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **variant**.| +| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **letiant**.| | ignorePunctuation | boolean | Yes | Yes | Whether punctuation is ignored. The value can be **true** or **false**. | | collation | string | Yes | Yes | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| | numeric | boolean | Yes | Yes | Whether numeric collation is used. The value can be **true** or **false**. | @@ -531,13 +580,14 @@ Represents the properties of a **Collator** object. constructor() -Create a **PluralRules** object. +Creates a **PluralRules** object to obtain the singular-plural type of numbers. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var pluralRules = new Intl.PluralRules(); + ```js + // Use the system locale to create a PluralRules object. + let pluralRules = new Intl.PluralRules(); ``` @@ -545,19 +595,21 @@ Create a **PluralRules** object. constructor(locale: string | Array<string>, options?: PluralRulesOptions) -Create a **PluralRules** object. +Creates a **PluralRules** object to obtain the singular-plural type of numbers. **System capability**: SystemCapability.Global.I18n -Parameters -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. | **Example** - ``` - var pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); + ```js + // Use locale zh-CN to create a PluralRules object. Set localeMatcher to lookup and type to cardinal. + let pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); ``` @@ -575,16 +627,23 @@ Obtains a string that represents the singular-plural type of the specified numbe | ---- | ------ | ---- | ------------ | | n | number | Yes | Number for which the singular-plural type is to be obtained.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------------------------------------- | | string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| **Example** - ``` - var pluralRules = new Intl.PluralRules("zh-Hans"); - pluralRules.select(1); + ```js + // Use locale zh-Hans to create a PluralRules object. + let zhPluralRules = new Intl.PluralRules("zh-Hans"); + // Determine the singular-plural type corresponding to number 1 in locale zh-Hans. + let plural = zhPluralRules.select(1); // plural = other + + // Use locale en-US to create a PluralRules object. + let enPluralRules = new Intl.PluralRules("en-US"); + // Determine the singular-plural type corresponding to number 1 in locale en-US. + plural = enPluralRules.select(1); // plural = one ``` @@ -594,7 +653,7 @@ Represents the properties of a **PluralRules** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------------------ | ------ | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | type | string | Yes | Yes | Sorting type. The value can be **cardinal** or **ordinal**. | @@ -617,8 +676,9 @@ Creates a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat(); + ```js + // Use the system locale to create a RelativeTimeFormat object. + let relativetimefmt = new Intl.RelativeTimeFormat(); ``` @@ -632,14 +692,15 @@ Creates a **RelativeTimeFormat** object. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| | options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. | **Example** - ``` - var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); + ```js + // Use locale zh-CN to create a RelativeTimeFormat object. Set localeMatcher to lookup, numeric to always, and style to long. + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); ``` @@ -658,16 +719,18 @@ Formats the value and unit based on the specified locale and formatting options. | value | number | Yes | Value to format. | | unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------- | | string | Relative time after formatting.| **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); - relativetimefmt.format(3, "quarter") + ```js + // Use locale zh-CN to create a RelativeTimeFormat object. + let relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); + // Obtain the localized representation (in unit of quarter) of number 3 in locale zh-CN. + let formatResult = relativetimefmt.format(3, "quarter"); // formatResult = "3 quarters later" ``` @@ -675,7 +738,7 @@ Formats the value and unit based on the specified locale and formatting options. formatToParts(value: number, unit: string): Array<object> -Returns an array of RelativeTimeFormat objects in parts for locale-aware formatting. +Obtains an array of RelativeTimeFormat objects in parts for locale-aware formatting. **System capability**: SystemCapability.Global.I18n @@ -686,16 +749,17 @@ Returns an array of RelativeTimeFormat objects in parts for locale-aware formatt | value | number | Yes | Value to format. | | unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -**Return Value** +**Return value** | Type | Description | | ------------------- | --------------------------- | | Array<object> | An array of **RelativeTimeFormat** objects in parts.| **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); - var parts = relativetimefmt.format(10, "seconds"); + ```js + // Use locale en to create a RelativeTimeFormat object. Set numeric to auto. + let relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); + let parts = relativetimefmt.formatToParts(10, "seconds"); // parts = [ {type: "literal", value: "in"}, {type: "integer", value: 10, unit: "second"}, {type: "literal", value: "seconds"} ] ``` @@ -707,16 +771,19 @@ Obtains the formatting options for **RelativeTimeFormat** objects. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ---------------------------------------- | --------------------------------- | | [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions8) | Formatting options for **RelativeTimeFormat** objects.| **Example** - ``` - var relativetimefmt= new Intl.RelativeTimeFormat("en-GB"); - relativetimefmt.resolvedOptions(); + ```js + // Use locale en-GB to create a RelativeTimeFormat object. + let relativetimefmt= new Intl.RelativeTimeFormat("en-GB", { style: "short" }); + // Obtain the options of the RelativeTimeFormat object. + let options = relativetimefmt.resolvedOptions(); + let style = options.style; // style = "short" ``` @@ -726,20 +793,20 @@ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------- | ------ | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | | style | string | Yes | Yes | Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| -## RelativeTimeFormatResolvedOptions8+ +## RelativeTimeFormatResolvedOptions8+ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------ | ---- | ---- | ---------------------------------------- | | locale | string | Yes | Yes | A string containing locale information, including the language, optional script, and region. | | numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | diff --git a/en/application-dev/reference/errorcodes/errorcode-i18n.md b/en/application-dev/reference/errorcodes/errorcode-i18n.md index 71555203e62a93f1c8cdfcfaf5f46ed04832c681..8a1392286491b7e7173d26a2e62c740de4abdbdf 100644 --- a/en/application-dev/reference/errorcodes/errorcode-i18n.md +++ b/en/application-dev/reference/errorcodes/errorcode-i18n.md @@ -1,4 +1,4 @@ -# I18N Error Codes +# i18n Error Codes ## 890001 Incorrect Parameter Type