提交 ab667b61 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 579d38b4
# Internationalization # Internationalization
- [Internationalization Overview](international-overview.md) - [Internationalization Overview](international-overview.md)
- [Internationalization Development (intl)](intl-guidelines.md) - [intl Development](intl-guidelines.md)
- [Internationalization Development (i18n)](i18n-guidelines.md) - [i18n Development](i18n-guidelines.md)
# 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 ### Available APIs
| Module | API | Description | | Class | API | Description |
| -------- | -------- | -------- | | --------- | ---------------------------------------- | --------------------- |
| ohos.i18n | getSystemLanguage(): string | Obtains the system language. | | System | getDisplayCountry(country:string,locale:string,sentenceCase?:boolean):string<sup>9+</sup> | Obtains the localized representation of a country. |
| ohos.i18n | getSystemRegion(): string | Obtains the system region. | | System | getDisplayLanguage(language:string,locale:string,sentenceCase?:boolean):string<sup>9+</sup> | Obtains the localized representation of a language. |
| ohos.i18n | getSystemLocale(): string | Obtains the system locale. | | System | getSystemLanguages():Array<string><sup>9+</sup> | Obtains the system language list. |
| ohos.i18n | isRTL(locale: string): boolean<sup>7+</sup> | Checks whether the locale uses a right-to-left (RTL) language. | | System | getSystemCountries(language: string):Array<string><sup>9+</sup> | Obtains the list of countries and regions supported for the specified language. |
| ohos.i18n | is24HourClock(): boolean<sup>7+</sup> | Checks whether the system uses a 24-hour clock. | | System | isSuggested(language: string, region?: string): boolean<sup>9+</sup> | Checks whether the system language matches the specified region. |
| ohos.i18n | getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a language. | | System | getSystemLanguage():string<sup>9+</sup> | Obtains the system language. |
| ohos.i18n | getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string | Obtains the localized display of a country name. | | System | setSystemLanguage(language: string)<sup>9+</sup> | Sets the system language. |
| System | getSystemRegion():string<sup>9+</sup> | Obtains the system region. |
| System | setSystemRegion(region: string)<sup>9+</sup> | Sets the system region. |
| System | getSystemLocale():string<sup>9+</sup> | Obtains the system locale. |
| System | setSystemLocale(locale: string)<sup>9+</sup> | Sets the system locale. |
| System | is24HourClock():boolean<sup>9+</sup> | Checks whether the 24-hour clock is used. |
| System | set24HourClock():boolean<sup>9+</sup> | Sets the 24-hour clock. |
| System | addPreferredLanguage(language: string, index?: number)<sup>9+</sup> | Adds a preferred language to the specified position on the preferred language list. |
| System | removePreferredLanguage(index: number)<sup>9+</sup> | Deletes a preferred language from the specified position on the preferred language list. |
| System | getPreferredLanguageList()<sup>9+</sup> | Obtains the preferred language list. |
| System | getFirstPreferredLanguage()<sup>9+</sup> | Obtains the first language in the preferred language list. |
| System | getAppPreferredLanguage()<sup>9+</sup> | Obtains the preferred language of an application. |
| System | setUsingLocalDigit(flag: boolean)<sup>9+</sup> | Sets whether to enable the local digit switch. |
| System | getUsingLocalDigit()<sup>9+</sup> | Checks whether the local digit switch is turned on. |
| | isRTL(locale:string):boolean<sup>9+</sup> | Checks whether the locale uses a right-to-left (RTL) language.|
### How to Develop ### How to Develop
1. Import the **i18n** module.
1. Obtain the system language. ```js
import I18n from '@ohos.i18n'
```
Call the **getSystemLanguage** method to obtain the system language (**i18n** is the name of the imported module). 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 ```js
let language = i18n.getSystemLanguage(); 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}`)
}
``` ```
2. Obtain the system region. 3. Obtain and set the system locale.
Call the **getSystemRegion** method to obtain the system region. 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 ```js
let region = i18n.getSystemRegion(); 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}`)
}
``` ```
3. Obtain the system locale. 4. Obtain and set the system locale.
Call the **getSystemLocale** method to obtain 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 ```js
let locale = i18n.getSystemLocale(); 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}`)
}
``` ```
4. Check whether the locale's language is RTL. 5. Check whether the locale uses a right-to-left (RTL) language.
Call the **isRTL** method to check whether the locale's language is RTL.
Call **isRTL** to check whether the locale uses an RTL language.
```js ```js
let rtl = i18n.isRTL("zh-CN"); 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}`)
}
``` ```
5. Check whether the system uses a 24-hour clock. 6. Obtain and set the 24-hour clock.
Call the **is24HourClock** method to check whether the system uses a 24-hour clock. Call **set24HourClock** to enable the 24-hour clock.
Call **is24HourClock** to check whether the 24-hour clock is enabled.
```js ```js
let hourClock = i18n.is24HourClock(); 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}`)
}
``` ```
6. Obtain the localized display of a language. 7. Obtain the localized representation of a language.
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. 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.
```js ```js
try {
let language = "en"; let language = "en";
let locale = "zh-CN"; let locale = "zh-CN";
let sentenceCase = false; let sentenceCase = false;
let localizedLanguage = i18n.getDisplayLanguage(language, locale, sentenceCase); 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}`)
}
``` ```
7. Obtain the localized display of a country. 8. Obtain the localized representation of a country.
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. 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 ```js
try {
let country = "US"; let country = "US";
let locale = "zh-CN"; let locale = "zh-CN";
let sentenceCase = false; let sentenceCase = false;
let localizedCountry = i18n.getDisplayCountry(country, locale, sentenceCase); 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}`)
}
``` ```
9. Obtain the list of system languages and the list of countries supported by a system language.
## Obtaining Calendar Information 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
[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. 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}`)
}
```
10. Check whether the language matches a country or region.
### Available APIs 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}`)
}
```
11. Obtain and set the preferred language.
| Module | API | Description | 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.)
| ohos.i18n | getCalendar(locale: string, type?: string): Calendar<sup>8+</sup> | Obtains the **Calendar** object for a specific locale and type. | Call **getPreferredLanguageList** to obtain the preferred language list.
| ohos.i18n | setTime(date: Date): void<sup>8+</sup> | Sets the date for the **Calendar** object. | Call **getFirstPreferredLanguage** to obtain the first preferred language in the preferred language list.
| ohos.i18n | setTime(time: number): void<sup>8+</sup> | Sets the time for the **Calendar** object. | 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.
| ohos.i18n | set(year: number, month: number, date: number, hour?: number, minute?: number, second?: number): void<sup>8+</sup> | Sets the year, month, day, hour, minute, and second for the **Calendar** object. |
| ohos.i18n | setTimeZone(timezone: string): void<sup>8+</sup> | Sets the time zone for the **Calendar** object. |
| ohos.i18n | getTimeZone(): string<sup>8+</sup> | Obtains the time zone for the **Calendar** object. |
| ohos.i18n | getFirstDayOfWeek(): number<sup>8+</sup> | Obtains the first day of a week for the **Calendar** object. |
| ohos.i18n | setFirstDayOfWeek(value: number): void<sup>8+</sup> | Sets the first day of a week for the **Calendar** object. |
| ohos.i18n | getMinimalDaysInFirstWeek(): number<sup>8+</sup> | Obtains the minimum count of days in the first week of a year. |
| ohos.i18n | setMinimalDaysInFirstWeek(value: number): void<sup>8+</sup> | Sets the minimum count of days in the first week of a year. |
| ohos.i18n | getDisplayName(locale: string): string<sup>8+</sup> | Obtains the localized display of the **Calendar** object. |
| ohos.i18n | isWeekend(date?: Date): boolean<sup>8+</sup> | Checks whether a given date is a weekend. |
```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.
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".
```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.
[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.
### Available APIs
| Class | API | Description |
| --------- | ---------------------------------------- | --------------------- |
| | getCalendar(locale:string,type?:string):Calendar<sup>8+</sup> | Obtains the **Calendar** object for a specific locale and type.|
| Calendar | setTime(date:Date): void<sup>8+</sup> | Sets the date for this **Calendar** object. |
| Calendar | setTime(time:number): void<sup>8+</sup> | Sets the date for this **Calendar** object. |
| Calendar | set(year:number,month:number,date:number,hour?:number,minute?:number,second?:number): void<sup>8+</sup> | Sets the year, month, day, hour, minute, and second for this **Calendar** object. |
| Calendar | setTimeZone(timezone:string): void<sup>8+</sup> | Sets the time zone of this **Calendar** object. |
| Calendar | getTimeZone():string<sup>8+</sup> | Obtains the time zone of this **Calendar** object. |
| Calendar | getFirstDayOfWeek():number<sup>8+</sup> | Obtains the start day of a week for this **Calendar** object. |
| Calendar | setFirstDayOfWeek(value:number): void<sup>8+</sup> | Sets the first day of a week for the **Calendar** object. |
| Calendar | getMinimalDaysInFirstWeek():number<sup>8+</sup> | Obtains the minimum number of days in the first week of a year. |
| Calendar | setMinimalDaysInFirstWeek(value:number): void<sup>8+</sup> | Sets the minimum number of days in the first week of a year. |
| Calendar | getDisplayName(locale:string):string<sup>8+</sup> | Obtains the localized display of the **Calendar** object. |
| Calendar | isWeekend(date?:Date):boolean<sup>8+</sup> | Checks whether the specified date in this **Calendar** object is a weekend. |
### How to Develop ### How to Develop
1. Instantiate a **Calendar** object. 1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
```
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. 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 ```js
let calendar = i18n.getCalendar("zh-CN", "gregory"); 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 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. 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.
```js ```js
let date1 = new Date(); let date1 = new Date();
...@@ -132,120 +249,122 @@ You can use APIs provided in the following table to obtain the system language a ...@@ -132,120 +249,122 @@ You can use APIs provided in the following table to obtain the system language a
calendar.setTime(date2); 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. Call **set** to set the year, month, day, hour, minute, and second for the **Calendar** object.
```js ```js
calendar.set(2021, 12, 21, 6, 0, 0) calendar.set(2021, 12, 21, 6, 0, 0)
``` ```
4. Set and obtain the time zone for the **Calendar** object. 5. 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.
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"); calendar.setTimeZone("Asia/Shanghai");
let 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); calendar.setFirstDayOfWeek(1);
let 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); calendar.setMinimalDaysInFirstWeek(3);
let 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.
Call the **getDisplayName** method to obtain the localized display of the **Calendar** object.
```js ```js
let localizedName = calendar.getDisplayName("zh-CN"); let localizedName = calendar.getDisplayName("zh-CN"); // localizedName = " Lunar Calendar"
``` ```
8. Check whether a date is a weekend. 9. Check whether a date is a weekend.
Call the **isWeekend** method to determine whether the input date is a weekend.
Call **isWeekend** to determine whether the input date is a weekend.
```js ```js
let date = new Date(); let date = new Date(2022, 12, 12, 12, 12, 12);
let weekend = calendar.isWeekend(date); let weekend = calendar.isWeekend(date); // weekend = false
``` ```
## Formatting a Phone Number ## Formatting a Phone Number
[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. [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.
### Available APIs ### Available APIs
| Module | API | Description | | Class | API | Description |
| -------- | -------- | -------- | | --------- | ---------------------------------------- | ----------------------- |
| ohos.i18n | constructor(country: string, options?: PhoneNumberFormatOptions)<sup>8+</sup> | Instantiates a **PhoneNumberFormat** object. | | PhoneNumberFormat | constructor(country:string,options?:PhoneNumberFormatOptions)<sup>8+</sup> | Instantiates a **PhoneNumberFormat** object.|
| ohos.i18n | isValidNumber(number: string): boolean<sup>8+</sup> | Checks whether the value of **number** is a phone number in the correct format. | | PhoneNumberFormat | isValidNumber(number:string):boolean<sup>8+</sup> | Checks whether the value of **number** is a phone number in the correct format.|
| ohos.i18n | format(number: string): string<sup>8+</sup> | Formats the value of **number** based on the specified country and style. | | PhoneNumberFormat | format(number:string):string<sup>8+</sup> | Formats the value of **number** based on the specified country and style. |
| PhoneNumberFormat | getLocationName(number: string, locale: string): string<sup>9+</sup> | Obtains the home location of a phone number. |
### How to Develop ### 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. Instantiate a **PhoneNumberFormat** object.
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 ```js
let phoneNumberFormat = new i18n.PhoneNumberFormat("CN", {type: "E164"}); let phoneNumberFormat = new I18n.PhoneNumberFormat("CN", {type: "E164"});
``` ```
2. Check whether the phone number format is correct. 3. Check whether the phone number format is correct.
Call the **isValidNumber** method to check whether the format of the input phone number is correct.
Call **isValidNumber** to check whether the format of the input phone number is correct.
```js ```js
let validNumber = phoneNumberFormat.isValidNumber("15812341234"); let validNumber = phoneNumberFormat.isValidNumber("15812341234"); // validNumber = true
``` ```
3. Format a phone number. 4. Format a phone number.
Call the **format** method of **PhoneNumberFormat** to format the input phone number.
Call **format** to format the input phone number.
```js ```js
let formattedNumber = phoneNumberFormat.format("15812341234"); let formattedNumber = phoneNumberFormat.format("15812341234"); // formattedNumber = "+8615812341234"
``` ```
## Measurement Conversion ## Measurement Conversion
The **unitConvert** API is provided to help you implement measurement conversion. The **I18NUtil** class provides an API to implement measurement conversion.
### Available APIs ### Available APIs
| Module | API | Description | | Class | API | Description |
| -------- | -------- | -------- | | --------- | ---------------------------------------- | --------------------------------------- |
| ohos.i18n | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string<sup>8+</sup> | Converts one measurement unit (**fromUnit**) into another (**toUnit**) and formats the unit based on the specified locale and style. | | I18NUtil | unitConvert(fromUnit:UnitInfo,toUnit:UnitInfo,value:number,locale:string,style?:string):string<sup>9+</sup> | Converts one measurement unit into another and formats the unit based on the specified locale and style.|
### How to Develop ### How to Develop
1. Convert a measurement unit. 1. Import the **i18n** module.
Call the [unitConvert](../reference/apis/js-apis-i18n.md#unitconvert9) method to convert a measurement unit and format the display result.
```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 ```js
let fromUnit = {unit: "cup", measureSystem: "US"}; let fromUnit = {unit: "cup", measureSystem: "US"};
...@@ -253,139 +372,361 @@ The **unitConvert** API is provided to help you implement measurement conversion ...@@ -253,139 +372,361 @@ The **unitConvert** API is provided to help you implement measurement conversion
let number = 1000; let number = 1000;
let locale = "en-US"; let locale = "en-US";
let style = "long"; let style = "long";
i18n.Util.unitConvert(fromUtil, toUtil, number, locale, style); let converttedUnit = I18n.I18NUtil.unitConvert(fromUnit, toUnit, number, locale, style); // converttedUnit = "236.588 liters"
``` ```
## Alphabet Indexing
## Alphabet Index [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.
[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.
### Available APIs ### Available APIs
| Module | API | Description | | Class | API | Description |
| -------- | -------- | -------- | | --------- | ---------------------------------------- | ----------------------- |
| ohos.i18n | getInstance(locale?: string): IndexUtil<sup>8+</sup> | Instantiates an **IndexUtil** object. | | | getInstance(locale?:string):IndexUtil<sup>8+</sup> | Instantiates an **IndexUtil** object. |
| ohos.i18n | getIndexList(): Array&lt;string&gt;<sup>8+</sup> | Obtains the index list of the current locale. | | IndexUtil | getIndexList():Array&lt;string&gt;<sup>8+</sup> | Obtains the index list of the current locale. |
| ohos.i18n | addLocale(locale: string): void<sup>8+</sup> | Adds the index of a new locale to the index list. | | IndexUtil | addLocale(locale:string): void<sup>8+</sup> | Adds the index of a new locale to the index list.|
| ohos.i18n | getIndex(text: string): string<sup>8+</sup> | Obtains the index of **text**. | | IndexUtil | getIndex(text:string):string<sup>8+</sup> | Obtains the index of a text object. |
### How to Develop ### How to Develop
1. Instantiate an **IndexUtil** object. 1. Import the **i18n** module.
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. ```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 ```js
let indexUtil = i18n.getInstance("zh-CN"); let indexUtil = I18n.getInstance("zh-CN");
``` ```
2. Obtain the index list. 3. Obtain the index list.
Call the **getIndexList** method to obtain the alphabet index list of the current locale. Call **getIndexList** to obtain the alphabet index list of the current locale.
```js ```js
let indexList = indexUtil.getIndexList(); let indexList = indexUtil.getIndexList(); // indexList = ["...", "A", "B", "C", ..., "X", "Y", "Z", "..."]
``` ```
3. Add an index. 4. Add an index.
Call the **addLocale** method to add the alphabet index of a new locale to the current index list. Call **addLocale** to add the alphabet index of a new locale to the current index list.
```js ```js
indexUtil.addLocale("ar") indexUtil.addLocale("ar")
``` ```
4. Obtain the index of a string. 5. Obtain the index of a string.
Call the **getIndex** method to obtain the alphabet index of a string. Call **getIndex** to obtain the alphabet index of a string.
```js ```js
let text = "access index"; let text = "access index";
indexUtil.getIndex(text); let index = indexUtil.getIndex(text); // index = "A"
``` ```
## Obtaining Line Breaks of Text ## Obtaining Line Breaks of Text
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. 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 ### Available APIs
| Module | API | Description | | Class | API | Description |
| -------- | -------- | -------- | | --------- | ---------------------------------------- | ------------------------------ |
| ohos.i18n | getLineInstance(locale: string): BreakIterator<sup>8+</sup> | Instantiates a **BreakIterator** object. | | | getLineInstance(locale:string):BreakIterator<sup>8+</sup> | Instantiates a **BreakIterator** object. |
| ohos.i18n | setLineBreakText(text: string): void<sup>8+</sup> | Sets the text to be processed. | | BreakIterator | setLineBreakText(text:string): void<sup>8+</sup> | Sets the text to be processed. |
| ohos.i18n | getLineBreakText(): string<sup>8+</sup> | Obtains the text to be processed. | | BreakIterator | getLineBreakText():string<sup>8+</sup> | Obtains the text to be processed. |
| ohos.i18n | current(): number<sup>8+</sup> | Obtains the current position of a **BreakIterator** object in the text being processed. | | BreakIterator | current():number<sup>8+</sup> | Obtains the current position of a **BreakIterator** object in the text being processed. |
| ohos.i18n | first(): number<sup>8+</sup> | Sets a **BreakIterator** object to the first breakable point. | | BreakIterator | first():number<sup>8+</sup> | Sets a **BreakIterator** object to the first breakable point. |
| ohos.i18n | last(): number<sup>8+</sup> | Sets a **BreakIterator** object to the last breakable point. | | BreakIterator | last():number<sup>8+</sup> | Sets a **BreakIterator** object to the last breakable point. |
| ohos.i18n | next(index?: number): number<sup>8+</sup> | Moves a **BreakIterator** object to the break point according to **index**. | | BreakIterator | next(index?:number):number<sup>8+</sup> | Moves a **BreakIterator** object to the break point according to **index**. |
| ohos.i18n | previous(): number<sup>8+</sup> | Moves a **BreakIterator** object to the previous break point. | | BreakIterator | previous():number<sup>8+</sup> | Moves a **BreakIterator** object to the previous break point. |
| ohos.i18n | following(offset: number): number<sup>8+</sup> | Moves a **BreakIterator** object to the break point following the position specified by **offset**. | | BreakIterator | following(offset:number):number<sup>8+</sup> | Moves a **BreakIterator** object to the break point following the position specified by **offset**.|
| ohos.i18n | isBoundary(offset: number): boolean<sup>8+</sup> | Determines whether a position is a break point. | | BreakIterator | isBoundary(offset:number):boolean<sup>8+</sup> | Determines whether a position is a break point. |
### How to Develop ### 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. Instantiate a **BreakIterator** object.
Call **getLineInstance** to instantiate a **BreakIterator** object.
```js ```js
let locale = "en-US" let locale = "en-US"
let breakIterator = i18n.getLineInstance(locale); let breakIterator = I18n.getLineInstance(locale);
``` ```
2. Set and access the text that requires line breaking. 3. Set and access the text that requires line breaking.
Call the **setLineBreakText** and **getLineBreakText** methods to set and access the text that requires line breaking.
Call **setLineBreakText** and **getLineBreakText** to set and access the text that requires line breaking.
```js ```js
let text = "Apple is my favorite fruit"; let text = "Apple is my favorite fruit";
breakIterator.setLineBreakText(text); breakIterator.setLineBreakText(text);
let breakText = breakIterator.getLineBreakText(); let breakText = breakIterator.getLineBreakText(); // breakText = "Apple is my favorite fruit"
``` ```
3. Obtain the current position of the **BreakIterator** object. 4. Obtain the current position of the **BreakIterator** object.
Call the **current** method to obtain the current position of the **BreakIterator** object in the text being processed.
Call **current** to obtain the current position of the **BreakIterator** object in the text being processed.
```js ```js
let pos = breakIterator.current(); let pos = breakIterator.current(); // pos = 0
``` ```
4. Set the position of a **BreakIterator** object. 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. 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 ```js
let firstPos = breakIterator.first(); // Set a BreakIterator object to the first break point, that is, the start position of the text. 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(); // Set a BreakIterator object to the last break point, that is, the position after the text end. 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. // 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 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. // If the object is moved out of the text length range, **-1** is returned.
let nextPos = breakIterator.next(-2); 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. 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. // 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); let followingPos = breakIterator.following(10); // Example: followingPos = 12
```
6. Determine whether a position is a break point.
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
```
## Obtaining the Time Zone
[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): TimeZone<sup>7+</sup> | Obtains a **TimeZone** object. |
| TimeZone | getID(): string<sup>7+</sup> | Obtains the time zone ID. |
| TimeZone | getDisplayName(locale?: string, isDST?: boolean): string<sup>7+</sup> | Obtains the localized representation of the time zone. |
| TimeZone | getRawOffset(): number<sup>7+</sup> | Obtains the offset between the time zone represented by a **TimeZone** object and the UTC time zone. |
| TimeZone | getOffset(date?: number): number<sup>7+</sup> | Obtains the offset between the time zone represented by a **TimeZone** object and the UTC time zone at a certain time point. |
| TimeZone | getAvailableIDs(): Array<string><sup>9+</sup> | Obtains the list of time zone IDs supported by the system. |
| TimeZone | getAvailableZoneCityIDs(): Array<string><sup>9+</sup> | Obtains the list of time zone city IDs supported by the system. |
| TimeZone | getCityDisplayName(cityID: string, locale: string): string<sup>9+</sup> | Obtains the localized representation of a time zone city in the specified locale. |
| TimeZone | getTimezoneFromCity(cityID: string): TimeZone<sup>9+</sup> | 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'
``` ```
5. Determine whether a position is a break point. 2. Instantiate the **TimeZone** object, and obtain the time zone information.
Call **getTimeZone** to obtain the **TimeZone** object.
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. ```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 ```js
let isboundary = breakIterator.isBoundary(5); 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
``` ```
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.
```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
| Class | API | Description |
| --------- | ---------------------------------------- | ------------------------------ |
| Transliterator | getAvailableIDs():Array<string><sup>9+</sup> | Obtains the transliterator ID list. |
| Transliterator | getInstance(): Transliterator<sup>9+</sup> | Creates a **Transliterator** object. |
| Transliterator | transform(text: string): string<sup>9+</sup> | 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): boolean<sup>9+</sup> | Checks whether the input character is a digit. |
| Unicode | isSpaceChar(char: string): boolean<sup>9+</sup> | Checks whether the input character is a space. |
| Unicode | isWhitespace(char: string): boolean<sup>9+</sup> | Checks whether the input character is a white space. |
| Unicode | isRTL(char: string): boolean<sup>9+</sup> | Checks whether the input character is of the RTL language. |
| Unicode | isIdeograph(char: string): boolean<sup>9+</sup> | Checks whether the input character is an ideographic character. |
| Unicode | isLetter(char: string): boolean<string><sup>9+</sup> | Checks whether the input character is a letter. |
| Unicode | isLowerCase(char: string): boolean<string><sup>9+</sup> | Checks whether the input character is a lowercase letter. |
| Unicode | isUpperCase(char: string): boolean<sup>9+</sup> | Checks whether the input character is an uppercase letter. |
| Unicode | getType(char: string): string<sup>9+</sup> | Obtains the type of a character.|
### How to Develop
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
```
2. Check the input character has a certain attribute.
Check whether the input character is a digit.
```js
let isDigit = I18n.Unicode.isDigit("1"); // isDigit = true
isDigit = I18n.Unicode.isDigit("a"); // isDigit = false
```
Check whether the input character is a space.
```js
let isSpaceChar = I18n.Unicode.isSpaceChar(" "); // isSpaceChar = true
isSpaceChar = I18n.Unicode.isSpaceChar("\n"); // isSpaceChar = false
```
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
```
Check whether the input character is an ideographic character.
```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
let isLetter = I18n.Unicode.isLetter("a"); // isLetter = true
isLetter = I18n.Unicode.isLetter("."); // isLetter = false
```
Check whether the input character is a lowercase letter.
```js
let isLowerCase = I18n.Unicode.isLowerCase("a"); // isLetter = true
isLowerCase = I18n.Unicode.isLowerCase("A"); // isLetter = false
```
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
```
## Obtaining the Sequence of Year, Month, and Day in a Date
### Available APIs
| Class | API | Description |
| --------- | ---------------------------------------- | ------------------------------ |
| I18NUtil | getDateOrder(locale: string): string<sup>9+</sup> | Checks the sequence of year, month, and day in a date. |
### How to Develop
1. Import the **i18n** module.
```js
import I18n from '@ohos.i18n'
```
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.
``` ```
# 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** 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.
>
> In the code snippets in this document, **intl** refers to the name of the imported module.
## Setting Locale Information ## 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 ### Available APIs
| Module | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.intl | constructor()<sup>8+</sup> | Instantiates a **Locale** object. | | Locale | constructor()<sup>8+</sup> | Instantiates a **Locale** object.|
| ohos.intl | constructor(locale?: string, options?: options) | Instantiates a **Locale** object based on the locale parameter and options. | | Locale | constructor(locale:string,options?:LocaleOptions) | Instantiates a **Locale** object based on the locale parameter and options.|
| ohos.intl | toString(): string | Converts locale information into a string. | | Locale | toString():string | Converts locale information into a string.|
| ohos.intl | maximize(): Locale | Maximizes locale information. | | Locale | maximize():Locale | Maximizes locale information.|
| ohos.intl | minimize(): Locale | Minimizes locale information. | | Locale | minimize():Locale | Minimizes locale information.|
### How to Develop ### 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 (-). 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. - 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. - 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. - 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| | Extended Parameter ID| Description|
| -------- | -------- | | -------- | -------- |
| ca | Calendar algorithm.| | ca | Calendar algorithm.|
...@@ -40,305 +44,346 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim ...@@ -40,305 +44,346 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim
| hc | Hour cycle.| | hc | Hour cycle.|
| nu | Numbering system.| | nu | Numbering system.|
| kn | Whether numeric collation is used when sorting or comparing strings.| | 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 ```js
let locale = "zh-CN"; let locale = "zh-CN";
let options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"}; let options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"};
let localeObj = new intl.Locale(locale, options); 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 ```js
let 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 ```js
let 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 ```js
let minimizedLocale = localeObj.minimize(); let minimizedLocale = localeObj.minimize();
let minimizedLocaleStr = minimizedLocale.toString(); // zh-u-ca-chinese-co-pinyin-kf-false
``` ```
## Formatting the Date and Time ## 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 ### Available APIs
| Module | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.intl | constructor()<sup>8+</sup> | Creates a **DateTimeFormat** object. | | DateTimeFormat | constructor()<sup>8+</sup> | Creates a **DateTimeFormat** object.|
| ohos.intl | constructor(locale: string \| Array&lt;string&gt;, options?: DateTimeOptions) | Creates a **DateTimeFormat** object and sets the locale and other formatting-related attributes. | | DateTimeFormat | constructor(locale:string\|Array&lt;string&gt;,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. | | DateTimeFormat | 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. | | DateTimeFormat | 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 | resolvedOptions():DateTimeOptions | Obtains the related attributes of the **DateTimeFormat** object.|
### How to Develop ### How to Develop
1. Instantiate a **DateTimeFormat** object. 1. Import the **intl** module.
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. Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
```
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 ```js
let dateTimeFormat = new intl.DateTimeFormat(); let dateTimeFormat = new Intl.DateTimeFormat();
``` ```
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). 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 ```js
let options = {dateStyle: "full", timeStyle: "full"}; let options = {dateStyle: "full", timeStyle: "full"};
let dateTimeFormat = new intl.DateTimeFormat("zh-CN", options); let dateTimeFormat = new Intl.DateTimeFormat("zh-CN", options);
``` ```
2. Format the date and time. 3. 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. Call **format** to format a **Date** object. A string is returned as the formatting result.
```js ```js
let date = new Date(); let options = {dateStyle: "full", timeStyle: "full"};
let formatResult = dateTimeFormat.format(date); 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"
``` ```
3. Format a period. 4. Format a period.
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 **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 ```js
let startDate = new Date(2021, 11, 17, 3, 24, 0); let startDate = new Date(2021, 11, 17, 3, 24, 0);
let endDate = new Date(2021, 11, 18, 3, 24, 0); let endDate = new Date(2021, 11, 18, 3, 24, 0);
let datefmt = new Intl.DateTimeFormat("en-GB"); let datefmt = new Intl.DateTimeFormat("en-GB");
datefmt.formatRange(startDate, endDate); let formatRangeResult = datefmt.formatRange(startDate, endDate); // formatRangeResult = "17/12/2021-18/12/2021"
``` ```
4. Obtain attributes of the **DateTimeFormat** object. 5. Access the attributes of the **DateTimeFormat** object.
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 **resolvedOptions** to obtain an object that contains all related attributes and values of the **DateTimeFormat** object.
```js ```js
let options = dateTimeFormat.resolvedOptions(); 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"}
``` ```
## Number Formatting
## Formatting Numbers [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) provides APIs to implement the number formatting specific to a locale.
Use [NumberFormat](../reference/apis/js-apis-intl.md#numberformat) APIs to format numbers for a specific locale.
### Available APIs ### Available APIs
| Module | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.intl | constructor()<sup>8+</sup> | Creates a **NumberFormat** object. | | NumberFormat | constructor()<SUP>8+</SUP> | Creates a **NumberFormat** object for the specified locale.|
| ohos.intl | constructor(locale: string \| Array&lt;string&gt;, options?: NumberOptions) | Creates a **NumberFormat** object and sets the locale and other formatting-related attributes. | | NumberFormat | constructor(locale:string\|Array&lt;string&gt;,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. | | NumberFormat | 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 | resolvedOptions():NumberOptions | Obtains the attributes of the **NumberFormat** object.|
### How to Develop ### How to Develop
1. Instantiate a **NumberFormat** object. 1. Import the **intl** module.
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. Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
```
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 ```js
let numberFormat = new intl.NumberFormat(); let numberFormat = new Intl.NumberFormat();
``` ```
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). 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 ```js
let options = {compactDisplay: "short", notation: "compact"}; let options = {compactDisplay: "short", notation: "compact"};
let numberFormat = new intl.NumberFormat("zh-CN", options); let numberFormat = new Intl.NumberFormat("zh-CN", options);
``` ```
2. Format a number. 3. Format a number.
Call the **format** method to format a number. A string is returned as the formatting result. Call **format** to format a number. A string is returned as the formatting result.
```js ```js
let options = {compactDisplay: "short", notation: "compact"};
let numberFormat = new Intl.NumberFormat("zh-CN", options);
let number = 1234.5678 let number = 1234.5678
let formatResult = numberFormat.format(number); let formatResult = numberFormat.format(number); // formatResult = "1235"
``` ```
3. Obtain attributes of the **NumberFormat** object. 4. Access the attributes of the **NumberFormat** object.
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 **resolvedOptions** to obtain an object that contains all related attributes and values of the **NumberFormat** object.
```js ```js
let options = numberFormat.resolvedOptions(); 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"}
``` ```
## String Sorting
## Sorting Strings 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.
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.
### Available APIs ### Available APIs
| Module | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.intl | constructor()<sup>8+</sup> | Creates a **Collator** object. | | Collator | constructor()<sup>8+</sup> | Creates a **Collator** object.|
| ohos.intl | constructor(locale: string \| Array&lt;string&gt;, options?: CollatorOptions)<sup>8+</sup> | Creates a **Collator** object and sets the locale and other related attributes. | | Collator | constructor(locale:string\|Array&lt;string&gt;,options?:CollatorOptions)<sup>8+</sup> | Creates a **Collator** object and sets the locale and other related attributes.|
| ohos.intl | compare(first: string, second: string): number<sup>8+</sup> | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object. | | Collator | compare(first:string,second:string):number<sup>8+</sup> | Calculates the comparison result of two strings based on the locale and other attributes of the **Collator** object.|
| ohos.intl | resolvedOptions(): CollatorOptions<sup>8+</sup> | Obtains attributes of the **Collator** object. | | Collator | resolvedOptions():CollatorOptions<sup>8+</sup> | Obtains the attributes of the **Collator** object.|
### How to Develop ### How to Develop
1. Instantiate a **Collator** object. 1. Import the **intl** module.
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. Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
```
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 ```js
let collator = new intl.Collator(); let collator = new Intl.Collator();
``` ```
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). 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).
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 ```js
let collator= new intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort"}); let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"});
``` ```
2. Compare two strings. 3. 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. 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 ```js
let collator= new Intl.Collator("zh-CN", {localeMatcher: "best fit", usage: "sort", sensitivity: "case"});
let str1 = "first string"; let str1 = "first string";
let str2 = "second string"; let str2 = "second string";
let compareResult = collator.compare(str1, str2); let compareResult = collator.compare(str1, str2); // compareResult = -1
str1 = "first";
str2 = "First";
compareResult = collator.compare(str1, str2); // compareResult = -1
``` ```
3. Obtain attributes of the **Collator** object. 4. Access the attributes of the **Collator** object.
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 **resolvedOptions** to obtain an object that contains all related attributes and values of the **Collator** object.
```js ```js
let options = collator.resolvedOptions(); 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"}
``` ```
## Determining the Singular-Plural Type ## Determining the Singular-Plural Type
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. 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 ### Available APIs
| Module | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.intl | constructor()<sup>8+</sup> | Creates a **PluralRules** object. | | PluralRules | constructor()<sup>8+</sup> | Creates a **PluralRules** object.|
| ohos.intl | constructor(locale: string \| Array&lt;string&gt;, options?: PluralRulesOptions)<sup>8+</sup> | Creates a **PluralRules** object and sets the locale and other related attributes. | | PluralRules | constructor(locale:string\|Array&lt;string&gt;,options?:PluralRulesOptions)<sup>8+</sup> | Creates a **PluralRules** object and sets the locale and other related attributes.|
| ohos.intl | select(n: number): string<sup>8+</sup> | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object. | | PluralRules | select(n:number):string<sup>8+</sup> | Determines the singular-plural type based on the locale and other formatting-related attributes of the **PluralRules** object.|
### How to Develop ### How to Develop
1. Instantiate a **PluralRules** object. 1. Import the **intl** module.
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. Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
```
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 ```js
let pluralRules = new intl.PluralRules(); let pluralRules = new Intl.PluralRules();
``` ```
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). 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).
```js ```js
let pluralRules = new intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"}); let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
``` ```
2. Determine the singular-plural type. 3. 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**. 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 ```js
let pluralRules = new Intl.PluralRules("zh-CN", {localeMatcher: "best fit", type: "cardinal"});
let number = 1234.5678 let number = 1234.5678
let categoryResult = plurals.select(number); let categoryResult = pluralRules.select(number); // categoryResult = "other"
``` ```
## Formatting Relative Time
## Formatting the Relative Time [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) provides APIs to format the relative time for a specific locale.
Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md#relativetimeformat8) APIs to format the relative time for a specific locale.
### Available APIs ### Available APIs
| Module | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.intl | constructor()<sup>8+</sup> | Creates a **RelativeTimeFormat** object. | | RelativeTimeFormat | constructor()<sup>8+</sup> | Creates a **RelativeTimeFormat** object.|
| ohos.intl | constructor(locale: string \| Array&lt;string&gt;, options?: RelativeTimeFormatInputOptions)<sup>8+</sup> | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes. | | RelativeTimeFormat | constructor(locale:string\|Array&lt;string&gt;,options?:RelativeTimeFormatInputOptions)<sup>8+</sup> | Creates a **RelativeTimeFormat** object and sets the locale and other formatting-related attributes.|
| ohos.intl | format(value: number, unit: string): string<sup>8+</sup> | Calculates the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | | RelativeTimeFormat | format(value:number,unit:string):string<sup>8+</sup> | 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&lt;object&gt;<sup>8+</sup> | Returns each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object. | | RelativeTimeFormat | formatToParts(value:number,unit:string):Array&lt;object&gt;<sup>8+</sup> | Obtains each part of the relative time format based on the locale and other formatting-related attributes of the **RelativeTimeFormat** object.|
| ohos.intl | resolvedOptions(): RelativeTimeFormatResolvedOptions<sup>8+</sup> | Obtains attributes of the **RelativeTimeFormat** object. | | RelativeTimeFormat | resolvedOptions():RelativeTimeFormatResolvedOptions<sup>8+</sup> | Obtains the attributes of the **RelativeTimeFormat** object.|
### How to Develop ### How to Develop
1. Instantiate a **RelativeTimeFormat** object. 1. Import the **intl** module.
Importing an incorrect bundle can lead to unexpected API behavior.
```js
import Intl from '@ohos.intl'
```
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. 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 ```js
let 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#relativetimeformatinputoptions9).
```js ```js
let 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 ```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2; let number = 2;
let unit = "year" let unit = "year"
let formatResult = relativeTimeFormat.format(number, unit); 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 ```js
let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {numeric: "always", style: "long"});
let number = 2; let number = 2;
let unit = "year" let unit = "year"
let formatResult = relativeTimeFormat.formatToParts(number, unit); 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 ```js
let 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 ## Samples
......
# @ohos.i18n (Internationalization) # @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 **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 [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** > **NOTE**
......
# @ohos.intl (Internationalization) # @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](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. 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.
> **NOTE** > **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. > - 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.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册